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...
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.
It's simple there are total 8 process in parallel.
You can count the leaf nodes which is
8
so total 8 processes.Explanation : parent
p
calledfork()
2 process1c
first child and parentp
.Now the secondfork()
is for both the processes. so the process1c
,2c
,3c
,p
. So on and you get 8 processes after thirdfork()
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.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.
Like @Mat said, 8 processes are created.
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.