Q:

Trouble Understanding Fork Logic

Can someone help me understand what is happening in this segment of code?  I am having trouble understanding why the output is how it is.  Output is:

0 1 2 3 4 
3
2
1
0

int main() {
   int i;

   for (i = 0; i < 5 && !fork(); i++) {
      fflush(stdout);
      printf("%d ", i);
   }
   wait(NULL);

   printf("\n");
   return 0;
}

A:

Two things here:
First, fork() return 0 in child process while it returns a non zero pid to the parent process. 
Second, short circuit of &&.
So in the beginning of the first process (p0), it runs to i < 5 && !fork(). Now i = 0 and another process created (p1). Now for p0, test !fork() fails, it ends the for loop and waiting for child to end.  For p1, the test succeeds, and print out 0, then increment i to 1, then it will create process p2 and itself goes out the for loop as p0 did.
Because of short circuiting, when i equals 5, no more fork will be called. 

