Ok, here's the code properly indented and with numbered lines.
1. printf("L1
");
2. if(fork() != 0) {
3. printf("L2
");
4. if(fork() != 0) {
5. printf("L3
");
6. fork();
7. }
8. }
9. printf("End
");
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
prints L1
. So far we have:
Process Tree:
1000
Output:
L1
Line2:
Process PID==1000
forks, creating a child process (assume it's PID==1001
). According to man 2 fork
only process PID==1000
is entering the if block, since fork()
will return 0
for the child process.
Process PID==1000
continues at Line 3 where it will print L2
and then continue to Line 5, whereas process PID==1001
jumps to Line 9, after the if
block, so it will print End
. So far, we have:
Process Tree:
-------------- 1000
|
|
1001
Output:
L1
L2
End
Line 4:
Process PID==1000
forks again, creating child process PID==1002
.
Again, process PID==1002
jumps to Line 9, printing End
because fork()
returns 0
for it, whereas father process PID==1000
continues at Line 5, printing L3
, and after that it's going to Line 6. So far we have:
Process Tree:
------------ 1000
| |
| |
1001 1002
Output:
L1
L2
End
L3
End
Line 6:
Father process PID==1000
forks again. creating child process PID==1003
. After that, both father and child processes go to Line 9, so they both print End
. So finally, we have:
Process Tree:
------------- 1000 --------------
| | |
| | |
1001 1002 1003
Output:
L1
L2
End
L3
End
End
End
To see that by yourself, you could change printf()
in your current code using getpid(2)
to see exactly what will be printed by each process. Code will be like this:
1. printf("(pid %d) L1
", (int) getpid());
2. if (fork() != 0) {
3. printf("(pid %d) L2
", (int) getpid());
4. if (fork() != 0) {
5. printf("(pid %d) L3
", (int) getpid());
6. fork();
7. }
8. }
9. printf("(pid %d) End
", (int) getpid());