fork(), problems with multiple children

2020-03-31 05:17发布

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

1条回答
乱世女痞
2楼-- · 2020-03-31 05:41

So, when you fork a process, the new process is an identical copy of the parent, so when your child continues from the if ((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 the fork-loop - you could use break; to exit the loop for example. Eventually, the child process should exit however.

In the OTHER side, if you want to make sure this child is FINISHED before creating the next fork, you should use waitpid() or some other variant of wait. 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 your pid 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.

查看更多
登录 后发表回答