I edited a little bit :
for ( ii = 0; ii < nbEnfants; ++ii) {
switch (fork()){
case -1 : {
printf("\n\nSoucis avec fork() !!! \n\n");
exit(0);
};
case 0 : {
EEcrireMp(ii);
}break;
default : {
tabPidEnfants[ii] = p;
usleep(50000);
ELireMp(nbSect, nbEnfants,tabPidEnfants);
};
}
}
My problem : i get to many child, like a bomb of children spawning. How can i stop those child ? the break should stop it no ?
Thanks
So, when you
fork
a process, the new process is an identical copy of the parent, so when your child continues from theif ((pid = fork()) == 0) ...
, it will continue out into the for-loop and create more children.The child should use
exit(0)
when it's finished (or at least NOT continue thefork
-loop - you could usebreak;
to exit the loop for example. Eventually, the child process shouldexit
however.In the OTHER side, if you want to make sure this child is FINISHED before creating the next
fork
, you should usewaitpid()
or some other variant ofwait
. Of course, these will wait for the forked process to exit, so if the forked process doesn't exit, that's not going to work. But you need to have a strategy for how you deal with each process. If you want to have 20 forked processes running at once, then you will probably need to store yourpid
in an array, so you can track the processes later. One way or another, your main process should track and ensure the processes are finished before it finishes itself.