In the following pseudo code, how many child processes are created?
fork();
if(fork()==0)
fork();
fork();
I did not quite understand how if statement is executed and how many child of child processes are created within if statements.
CodePudding user response:
I'll try to see if we can visualise this
Line 1 - fork() generates parent and child_1
Now both of them start running the code
Line 2 - if(fork()==0) is run both in parent and child 1:
- parent: will generate parent and child_2
- child_1: will generate child_1 as parent and child_3.
Line 3 - fork() inside if condition, this if condition will be true only for child_2 and child_3, as fork() returns the the id of child when parent is running, and for child id is 0. As child_2 and child_3 are the Childs generated in if condition fork() their id will be 0. After this:
- child_2: will generate child_2 as parent and child_4.
- child_3: will generate child_3 as parent and child_5.
After this point we have parent, child_1, child_2, child_3, child_4, child_5 running in parallel.
Now the fork() in Line 4 are run by each of them generating child_6, child_7, child_8, child_9, child_10, child_11 respectively by each of the running process.
That leads to a total of 12 process out of which 1 is parent and 11 are Child processes.
Hence there are a total of 11 child processes.