In: Computer Science
int main(){
int i = 3;
if(fork()){
i++;
fork();
i+=3;
}else{
i+=4;
fork();
i+=5;
}
printf("%d\n",i);
}
how many processes does this code create including the parent
Lets see the code step by step and understand how many process are created including the parent.
Giving each fork() function a name as shown below so that we can understand easily :
int main(){
int i = 3;
if(fork()){ //fork1()
i++;
fork(); //fork2()
i+=3;
}else{
i+=4;
fork(); //fork3()
i+=5;
}
printf("%d\n",i);
}
While execution, when compiler will reach fork1(), a child process (say C1) of the parent process (say P1) will be created. The child process C1 will return 0 and the parent process P1 will return a positive integer. Hence if part will be executed by the parent process and else part by C1. First lets understand the if part by the parent process.
Parent process P1 will first increment the value of i and then while execution, when compiler will reach fork2(), again child process (say C2) of the parent process P1 will be created. Then both P1 and C2 will increment the value of i by 3.
Now lets understand the else part by the child process C1.
In else part, first C1 will increment the value of i by 4 and when compiler will reach fork3(), a child process (say C3) of the child process C1 (which is now acting as a parent) will be created. Then both C1 and C3 will increment the value of i by 5. And in this way, total 4 print() statements will execute.
So, Total number of processes created by the code including parent = 4.
If you have any doubt regarding the solution then let me know in comment. If it helps, kindly give an upVote to this answer.