Race Conditions in C

c, operating-system, race-condition

Solution

As far as `count` is concerned, there is no race: each of the two processes has its own separate `count`.

As to the order in which the characters of `"Output 1"` and `"Output 2"` appear on `stdout`, there is indeed a race: the two outputs can end up arbitrarily interleaved.

Problem

I'm having trouble analyzing a problem on a past OS exam. It is as follows: Describe the output of the following program. Does a race condition exist? ``` int count=0; int main(void) { pid_t pid; if( (pid = fork()) < 0) { perror("Fork error"); exit(1); } else if( pid == 0) { charatatime("Output 1\n"); } else { charatatime("Output 2\n"); } printf(“Count = %d”,count); exit(0); } static void charatatime(char * str) { char * ptr; int c; for(ptr = str; c = *ptr++; ) { count++; putc(c, stdout); } } ``` I'm not that good yet with C and race conditions, so my answer is mostly a guess. But if I saw this on an exam, I would say "The program splits a process into a parent and child process; the child process prints 'Output1' and the parent prints 'Output2', one character at a time. Then the total number of letters is printed at the end of the program; however, this variable 'count' may be inaccurate, as a race condition exists between the child and parent. Either can access and update count at any time, which can lead to inaccuracies." From my understanding, race conditions arise when two or more threads or processes try to access or set the same shared variable, and the only incident of that I can see in this program is 'count'. Am I anywhere near correct, and if not, what could be added to this program to create a race condition (hypothetically, of course; I know that's not what we would want to do)?

Original source