printf("L1 \n");
if (fork() != 0) {
printf("L2 \n");
if (fork() != 0) {
printf("L3 \n");
fork();
}
}
printf("End \n");
I am having a hard time understanding this code. Could someone explain/ display what the process graph would look like? Also, a valid and invalid sequence.
My thought of the process graph was something like this:
L1 will hold two L2 processes then each L2 processes will hold 2 L3 processes and each L3 processes will hold an end processes. Is this correct?
A valid sequence for me was L1, L2, L3, End
An invalid one would be L2, L1, End this is because L1 must come before L2, L2 is dependent on L1.
Ok, here's the code properly indented and with numbered lines.
Let's assume that when you run it for the first time the father's PID is 1000 (it doesn't matter what number is it, anyway it depends on OS, but we're making this assumption to make it clear on the process tree).
Line1:
Process
PID==1000
printsL1
. So far we have:Process Tree:
Output:
Line2:
Process
PID==1000
forks, creating a child process (assume it'sPID==1001
). According toman 2 fork
only processPID==1000
is entering the if block, sincefork()
will return0
for the child process.Process
PID==1000
continues at Line 3 where it will printL2
and then continue to Line 5, whereas processPID==1001
jumps to Line 9, after theif
block, so it will printEnd
. So far, we have:Process Tree:
Output:
Line 4:
Process
PID==1000
forks again, creating child processPID==1002
.Again, process
PID==1002
jumps to Line 9, printingEnd
becausefork()
returns0
for it, whereas father processPID==1000
continues at Line 5, printingL3
, and after that it's going to Line 6. So far we have:Process Tree:
Output:
Line 6:
Father process
PID==1000
forks again. creating child processPID==1003
. After that, both father and child processes go to Line 9, so they both printEnd
. So finally, we have:Process Tree:
Output:
To see that by yourself, you could change
printf()
in your current code usinggetpid(2)
to see exactly what will be printed by each process. Code will be like this: