The child process begins executing at the exact point where the last one left off – after the fork statement. What if the statement contains multiple fork()s like the conditional expression like the following. Where exactly program execution starts for the child process. Before worrying about how many processes gets created, I wanted to know if every child process created tries to evaluate fork() && fork() || fork(); statement. If it is so. How does a child process that got created because of second fork() statement have information from the first fork() to evaluate fork() && fork().
main(){
fork() && fork() || fork();
}
The child that results from the second
fork()knows about the results of the firstfork()because it is an exact copy of the parent process.You can work out what happens by drawing a little tree for yourself. Start with the first fork:
The parent gets back the PID of the
child1process, andchild1gets back 0. So we have something like:in the parent, and:
in the child. Short circuiting means that the middle
fork()of the original expression doesn’t get executed in the child, only in the parent. So now what happens to the tree?parentis the original process, and gets the PID ofchild2.child2, just likechild1, gets 0. What do our expressions look like now?Now, again by short-circuiting,
parentis done, and doesn’t execute the lastfork(). Bothchildandchild2have to, however. That leaves us with the following tree:And that’s it.
child1andchild2each get the PID of their respective children, andchild1-1andchild2-1each get back 0. Substituting those values in, the final expressions are:And that’s it – they all exit.