You have to check for parent-child starting from after your first fork. Every time you call fork()
you are spawning a child. What you are doing now is this:
- Starting executing 1 program (+1 proc, 1 proc total)
- First
fork()
: Main program spawns child (+1 proc, 2 procs total) - Second
fork()
: Child and main program spawn children. (+2 procs, 4 procs total) - Third
fork()
: All processes previously mentioned spawn children(+4 procs, 8 procs total).
The resulting process tree from your original code would look like this:
pi
/ | \
pi pi pi
/ | |
pi pi pi
|
pi
Possible solution(works for n-children):
int noProcs = 3;
int i;
for (i = 0; i < noProcs; ++i) {
if (fork() == 0) {
printf("in child\n");
//Do stuff...
exit(0);
}
}
//DONT FORGET: Reap zombies using wait()/waitpid()/SIGCHLD etc...
Note that after every fork()
call, the children spawned are executing the same subsequent code. For each step in the loop's iteration, here's what happens after I spawn a child with fork()
:
- Child process: executes child code, and calls
exit()
. This prevents us from looping and creating more children than intended. - Parent process: Bypasses the
if(fork() == 0)
statement's body and steps through the loop, spawning additional children as specified.