Unix – fork() system call in c

cforkunix

    #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

Best Answer

Let's follow the fork-tree, assuming none of the forks fails

fork();

Now we have two processes, so far it doesn't matter who's child and who parent, call them p1 and p2

fork()

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

   && fork()

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 fork

              || fork();

here, spawning four new processes, giving a total of 6 + 4 = 10.

fork();

each of the 10 processes forks again, makes 20.

Related Topic