fork()
calls outside a loop are easy to figure out, but when they are inside a loop I find it difficult. Can anyone figuratively explain how the processes branch out with an example like this one?
#include <stdio.h>
int main(){
int i;
for(i=0;i<2;i++)
{
fork();
printf("hi");
fork();
}
exit(0);
}
Ideally, this would be the case:
The calculation could be done by following each event:
Now we add up the the number of hi's:
2 + 8 = 10 hi's in total
However, this is not necessarily the case. On different systems, you may get different results.
A call to fork() causes a child process to be spawned that is identical to the parent. If there is any buffering done when printing stdout and the buffers are not flushed before the next fork, then the child will appear to print when it "should not have". Refer to this question for some details on buffering.
This causes a different number of hi's to be printed an different systems.
Just unroll the loop:
I've used this code :
Now i've piped the output to fk.out.
Now look at this :
There, you have it, you have 8 processes !. Don't coun't hi's. Because stdin buffer will switched back and forth, so counting hi's will be ambiguous.