简体   繁体   English

C中的多叉示例

[英]Multiple Fork example in C

I am trying to have a program that uses multiple forks. 我正在尝试使用多个分叉的程序。
I used this example to get myself started Multiple fork() Concurrency 我用这个例子开始了自己的工作。Multiple fork()Concurrency

it works perfectly as is. 它按原样完美工作。 However, when I try to add a print statement in the child like this: 但是,当我尝试在子级中添加打印语句时,如下所示:

 if ((p = fork()) == 0) {
          // Child process: do your work here
        printf("child %i\n", ii);
          exit(0);
       }

The process never finishes. 该过程永远不会完成。 How can I do stuff in the child and get the parent to still finish execution of the program? 我该如何在孩子中做些事情并让父母仍然完成程序的执行?

In your example code 在您的示例代码中

if (waitpid(childPids[ii], NULL, WNOHANG) == 0) {

should be 应该

if (waitpid(childPids[ii], NULL, WNOHANG) == childPids[ii]) {

because of 因为

waitpid(): on success, returns the process ID of the child whose state has changed; waitpid():成功后,返回状态已更改的子进程的ID; on error, -1 is returned; 错误时,返回-1; if WNOHANG was specified and no child(ren) specified by pid has yet changed state, then 0 is returned. 如果指定了WNOHANG并且pid指定的子级尚未更改状态,则返回0。

Reference: http://linux.die.net/man/2/waitpid 参考: http : //linux.die.net/man/2/waitpid

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

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