D
D
doublench212014-10-24 07:41:02
linux
doublench21, 2014-10-24 07:41:02

How to achieve Race Condition in code?

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char const *argv[])
{
  int fork_status, i = 0, fd1[2], fd2[2], buff;
  printf("Hello...Get start:\n");


  if((pipe(fd1) == -1) && (pipe(fd2) == -1)) {
    fprintf(stderr, "pipe() error!\n");
  } else {
    fork_status = fork(); // Создаём процесс

    if(fork_status == -1) { // Ошибка
      fprintf(stderr, "fork() error!\n");
      exit(-1);
    } else if(fork_status == 0) { // Дочерний процесс
      while(1) {
        printf("Second thread work...\n");
        i++;
        sleep(3);
      }

    } else { // Родительский процесс
      while(1) {
        printf("First thread work...\n");
        if(i%2 == 0) {
          printf("i = %d\n", i);
        }
        sleep(3);
      }
    }
  }

  return 0;
}

The variable i in the child process is incremented, while in the parent process it is always zero.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
brutal_lobster, 2014-10-24
@brutal_lobster

stackoverflow.com/questions/13274786/how-to-share-...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question