In: Computer Science
Question: Including the initial parent process, how many processes are created by the program? And what is the value of i before each process terminates? Please draw the parent-child process hierarchy to justify your answer.
#include<stdio.h>
#include<unistd.h>
int main() {
int i = 0;
if (fork() == 0) {
++i;
if (fork() != 0)
i = 3;
else
++i;
fork();
} else {
i = 5;
if (fork() == 0)
++i;
}
return 0;
}
I could really use a longer explanation of this problem. I have seen the answer but I still don't really understand how to get to the answer. Any help would be greatly appreciated.
This program creates 6 processes . Each process terminates when it encounters "return 0;" , so printing the value of "i" just before that would give me the final value of "i" for that process before the process exits, so just put a printf() before that. I executed it and i got these 6 values { 5,2,2,3,3,6 } ( The order may differ ).
Now each process has its own process space and has its own variables i.e. it's own copy of " i " . Now when fork() system call is executed it returns the process number to the parent process and " 0 " to the child process and that's how we determine the flow of execution for each process.
Let's look at the following hierarchy and its path of execution :
THe main process forks() the process -2 and process -3 .. Then process -2 spawns process -4 . Later on Process -2 & 4 does fork() to create process -5 and process -6 .
So the final value of "i" for each process would be :
Main process (Process -1 ) : 5
Process -2 (Spawned by process -1 in first if {} condition ) : 2
Process -3 (Spawned by process -1 in else{} part ) : 6
Process -4 (Spawned by process -2 ) : 3
Process - 5 ( Spawned by process -2 ) : 2
Process - 6 (Spawned by process -4) : 3