简体   繁体   English

fork(),多个孩子的问题

[英]fork(), problems with multiple children

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 the if ((pid = fork()) == 0) ... , it will continue out into the for-loop and create more children. 因此,当您fork一个进程时,新进程是父进程的相同副本,因此当您的子进程继续if ((pid = fork()) == 0) ... ,它将继续进入for - 循环和创造更多的孩子。

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. 孩子在完成时应该使用exit(0) (或者至少不继续fork -loop - 你可以使用break;例如退出循环。最后,子进程应该exit

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 . 在OTHER方面,如果你想在创建下一个fork之前确保这个孩子已经完成,你应该使用waitpid()或其他一些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. 如果要同时运行20个分叉进程,则可能需要将pid存储在数组中,以便稍后跟踪进程。 One way or another, your main process should track and ensure the processes are finished before it finishes itself. 无论如何,您的主要流程应该跟踪并确保流程在完成之前完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM