Including the initial parent process, how many processes are created by the prog
ID: 2247646 • Letter: I
Question
Including the initial parent process, how many processes are created by the program shown below?
int main()
{
/* fork a child process */
fork();
/* fork another child process */
fork();
/* and fork another */
fork();
int i;
for (i=0; i <5; i++)
fork();/* fork another child process */
return 0;
}
Please show the work and explanation in details. I am tentive to say that the number of processes is 8 but I am not sure.
Explanation / Answer
The fork call creates one process each time that it is executed.
Once executed, The fork() method returns 0 in the new (child) process and the process id of the child (not zero) in the original (parent) process. Both processes then run through rest of the code after the fork call..
int main()
{
fork();
fork();
fork();
int i;
for (i=0; i <5; i++)
fork();/* fork another child process */
return 0;
}
Now in the above program, for sake of similicity, the for loop can be replaced with 5 calls of fork as below:
int main()
{
fork(); // Line 1
fork(); // Line 2
fork(); // Line 3
// replacing for loop
fork(); // Line 4
fork(); // Line 5
fork(); // Line 6
fork(); // Line 7
fork(); // Line 8
return 0;
}
Now, Once program starts, There is just one process P1.
Control reaches to line 1, In line 1, due to fork.. P process creates one new process P2.
Now once Line1 is done, both P1 and P2 moves to Line2.
P1 again create one new process P3. similarly P2, creates one new process P4.
So at the end of line 2, There are 4 processes in systsm P1, P2, P3 and P4..
Similarly these process will complete line 3 and there will be total 8 processes..
So at the end of line 8, there will be 2^8 process. Means 256 processes/