What would be the output of following fork() calls ?
func(){
fork();
fork();
fork() && fork() || fork();
fork();
print("Saikacollection\n");
}
Can anyone help me in getting the answer to this code as well as some explanations as I am new to OS ? I have found several questions on fork() on SO, but couldn’t figure out much.
Saikacollection will be printed
40times as output to the code. This can be explained as follows :-To understand the output, we need to know following :-
parent process.pid(process identifier) of the child to parent0to the child process.Consider the image shown :-
Convention : All the parents(callers) of the process are written to
leftand marked with astar.At the beginning, we have just 1 process, so a fork() call creates a child. Considering the root of the tree as level 1, we can see at level 2 , we have two processes, parent(left) and child(right) .
fork()fork() again further creates
4such processes, marked as 1, 2, 3, 4. Since all of the four processes will go through similar code structure further, we can say the total number of processes will be4times a single process producesfork()&&fork()||fork()Understanding this statement involves, realizing the fact that in C,
&& operator has more precedence than ||firstof two operands joined by&&goeswrong, wedon't check the second. Similarly, iffirstof the two operands of||istrue,we don't check the secondoperand.&&fork()for the parent at 4th level, returns a pid for one process, which terminates, while the child of that step, gets a 0. So, it goes for execution of||fork()||fork()call for child of level 5, further produces a process as a resultHad we done the same for all the three nodes, we could have got
5*4 = 20processes.fork()Final fork() just
doublesthe number of process available at that step.2*20 = 40.