fork(), problems with multiple children

亡梦爱人 提交于 2019-12-19 11:56:56

问题


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:


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.



来源:https://stackoverflow.com/questions/18547166/fork-problems-with-multiple-children

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!