why does fork program printf execute more time [du

2019-03-07 03:16发布

问题:

This question already has an answer here:

  • Output of fork() calls 3 answers

from the man page of fork i read fork create duplicate of parent process. But not able to understand why below program printf execute 8 times. I read Working of fork() in linux link also.

#include <stdio.h>
int main()
{
    fork();
    fork();
    fork();
    printf("process\n");
}

回答1:

In general for n forks in this manner will execute the next statements (in this case printf) 2^n times. Here is how:

|
+-fork()----------------------------------+
|                                         |
+-fork()-------------+                    +-fork()-------------+
|                    |                    |                    |
+-fork()---+         +-fork()---+         +-fork()---+         +-fork()---+
|          |         |          |         |          |         |          |
print()    print()   print()    print()   print()    print()   print()    print()


回答2:

Fork works like a binary tree. So its always 2^x number of processes on every x number of fork calls.

Lets understand with your example.

First fork() call:

When the first fork() is called. The parent process creates a new process. So we have 2 threads.

Second fork() call:

At this point we have two processes(main process and a new created process).These two threads will call second fork individually and create 2 new processes each. so we have 4 threads.

You might have got the idea by now. Every time a fork() is encountered all the processes create their respective child processes(double themselves).