I was reading about the fork
function and how it creates new processes. The following program runs fine and prints here
sixteen times, but, I am having trouble understanding the flow of execution:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>
int main()
{
int i;
for (i = 0; i < 4; i++) { // line no. 12
fork(); // line no. 13
}
printf("%s\n", "here");
return 0;
}
It seems to me that there are two ways this program can be viewed as:
1st approach: fork()
is called a total of four times. If I replace the loop with four calls to the fork()
function, things seem to fall in place and I understand why here
is printed 2 ^ 4
times.
2nd approach: fork()
spawns a new process exactly from where it is invoked and each of these child processes have their own local variables. So, after line no. 13, each of these child processes see the end of the loop (}
) and they go to line no. 12. Since, all these child processes have their own local variable i
set to 0 (maybe i
is set to some garbage value?), they all fork again. Again for these child processes their local variable i
is set to 0. This should result in a fork bomb.
I am certainly missing something in my 2nd approach could someone please help?
Thanks.
Your 2nd approach is not right. Because after fork()
the child process inherits the current value of i
. It's nneither set to 0
everytime fork()
is called nor do they have garbage value. So, your code can't have a fork bomb. The fact that it's a local variable is irrelevant. fork()
clones pretty much everything and the child process is identical to its parent except for certain things as noted in the POSIX manual.
I'll reduce the loop count to 2 for ease of explaining and assume all fork()
calls succeed:
for (i = 0; i < 2; i++) {
fork();
}
printf("%s\n", "here");
1) When i=0
, fork()
is executed and there are two processes now. Call them P1 and P2.
2) Now, each P1 and P2 processes continue with i=0 the loop and increment i
to 1. The for
loop condition is true, so each of them spawn another two processes and in total 4. Call them P1a & P1b and P2a & P2b. All 4 processes now have i=1 and increment it to 2 (as they continue the loop).
3) Now, all 4 processes have the value of i
as 2 and for loop condition is false in all of them and "here" will be printed 4 times (one by each process).
If it helps, you can convert the for
loop to a while
loop and how i
gets incremented by both processes returning from each fork()
might become a bit more clear:
i = 0;
while(i < 2) {
fork();
i++;
}
printf("%s\n", "here");