Reputation: 3347
I wrote two simple programs to understand the fork() API.
The first program:
int multiple_fork(){
fork(); //prints 2 times
fork(); //prints 4 times
printf("hello\n");
exit(0);
}
int main(){
multiple_fork();
return 0;
}
This program will print "hello" four times because the first fork() produces a child thread (C0), the second fork produces another two child threads C1 and C2 from parent thread (P) and C0, respectively. So far so good.
The second program:
#define N 2
int main(){
int status, i;
pid_t pid;
/* parent creates N children */
for(i = 0; i < N; i++)
if((pid = fork()) == 0){ /* Child */
printf("Child\n");
exit(100+i);
}
return 0;
}
This will print "Child" twice which I do not understand because I expect the "Child" get printed three times. Reason: in the first loop, one child process (C0) is generated so this child will print "Child" once. Since C0 contains the same address space as parent process P. Then both P and C0 will execute the second loop. So C1 and C2 are generated from P and C0, respectively. So for C1 and C2, each child process will print "Child" once. Therefore, it should print "Child" three times. But apparently, I am wrong. Could someone explain what has happened?
Upvotes: 0
Views: 125