why does fork program printf execute more time [du

2019-03-07 03:11发布

This question already has an answer here:

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");
}

2条回答
SAY GOODBYE
2楼-- · 2019-03-07 03:49

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()
查看更多
3楼-- · 2019-03-07 03:49

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).

enter image description here

查看更多
登录 后发表回答