So I have this function that forks N number of child processes. However it seems to be forking more than specified. Can you tell me what I\'m doing wrong? Thanks
When you fork
a process, you basically end up with two (almost) exact copies of the process and both of them will continue running.
So what's happening is that the children themselves are continuing the loop in the own process space (after they print their output) as well as the parent doing it. And, in fact, because these children are also forking, the grandchildren will also carry on from that point. I'm sure there's a formula for actually figuring out how many children you end up with (probably something like N!) but I don't have the energy to figure it out at the moment. Better to use the following solution.
The way to tell the difference between parent and child is the return value from fork
.
fork
failed.wait
for it).Here's some test code:
#include
#include
#include
void forkChildren (int nChildren) {
int i;
pid_t pid;
for (i = 1; i <= nChildren; i++) {
pid = fork();
if (pid == -1) {
/* error handling here, if needed */
return;
}
if (pid == 0) {
printf("I am a child: %d PID: %d\n",i, getpid());
sleep (5);
return;
}
}
}
int main (int argc, char *argv[]) {
if (argc < 2) {
forkChildren (2);
} else {
forkChildren (atoi (argv[1]));
}
return 0;
}
and some output to show you what's happening:
pax> forktest 5
I am a child: 1 PID: 4188
I am a child: 2 PID: 4180
I am a child: 3 PID: 5396
I am a child: 4 PID: 4316
I am a child: 5 PID: 4260
pax> _