#include <stdio.h>
#include <unistd.h>
int main()
{
fork();
fork() && fork() || fork();
fork();
printf("forked\n");
return 0;
}
It cause difficulty to understand how to calculate number of processes spawned after executing the program?
Help me to find out.
Platform –UBUNTU 10.04
Let’s follow the fork-tree, assuming none of the forks fails
Now we have two processes, so far it doesn’t matter who’s child and who parent, call them p1 and p2
Both of those processes spawn another child, so we have 4 processes, for two of them (p3, p4) the result is zero, for the other two (p1 and p2) it’s nonzero
p1 and p2 fork again, giving p5 and p6, six processes total. In p1 and p2, the
&&evaluates to true, so they don’t fork again in this line. For p3, p4, p5, p6, the&&evaluates to false, so they forkhere, spawning four new processes, giving a total of 6 + 4 = 10.
each of the 10 processes forks again, makes 20.