How many processes are forked here

2019-01-29 14:20发布

I know that it might come as a stupid question but could anyone help me understand the behavior of the following code snippet

//label 0
int main(){
  fork();//label 1
  fork();//label 2
  fork();//label 3
  return 0;
}

As far as I understand, the process tree goes like this

              [0]
          /    |    \
        [1]   [2]   [3]
       /  \    |
      [2] [3] [3]
       |
      [3]

Am I right? In case so, I am confused as to why the second fork doesn't spawn a process corresponding to label 1 fork and the third fork doesn't spawn any process any further. I mean a child process is the exact copy of the parent (at least in code) so it must execute the code of its parent in entirety. Can anyone please help me with this confusion...

标签: c process fork
4条回答
我只想做你的唯一
2楼-- · 2019-01-29 14:28

Yes, the child is a copy of its parent. It inherits execution state too, including where in the code the parent was executing. When the parent returns from the first fork() with the PID (>0) of the child, its first child returns with 0 and then continues on to the second and third forks. The child doesn't go back to the top of main(), it just goes on from after the fork that created it.

EDIT Re-word in response to comment. See the fork(2) man page for the meaning of all return values.

查看更多
男人必须洒脱
3楼-- · 2019-01-29 14:39

It's simple there are total 8 process in parallel.

p ----------------
|                 |          // first fork() 
1c-------         p -------   
|        |        |        |      // second fork()
2c---    1c---    3c---    p----  
|   |    |    |   |    |   |    |    // third fork()
4c  2c   1c   5c  6c  3c   7c   p  

You can count the leaf nodes which is 8 so total 8 processes.

Explanation : parent p called fork() 2 process 1c first child and parent p.Now the second fork() is for both the processes. so the process 1c,2c,3c,p. So on and you get 8 processes after third fork() call. After fork new process executes just after the code where it is forked. so all the code below the fork is for both parent and the child processes.

查看更多
Root(大扎)
4楼-- · 2019-01-29 14:40

The process tree looks like below. I used following naming convention for processes. prefix parent process name to the corresponding fork label that created it.

                [0]
          /      |      \
        [01]    [02]    [03]
       /  \       |
    [012] [013] [023]
     /
   [0123]

Like @Mat said, 8 processes are created.

查看更多
Rolldiameter
5楼-- · 2019-01-29 14:47

After the first fork, you have two processes. Both hit the second fork, creating four processes in total.

All four hit the third fork, so you have eight processes. Then they all exit.

查看更多
登录 后发表回答