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.