Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Fork wait和C中的管道_C_Pipe_Fork - Fatal编程技术网

Fork wait和C中的管道

Fork wait和C中的管道,c,pipe,fork,C,Pipe,Fork,我有一个任务,我们应该创建特定数量的子进程,比如说3个,让父进程等待每个子进程完成。我们还应该有一个所有进程都要写入的管道,这样一旦父进程完成等待,它就会使用管道输出所有子进程结果的总和 到目前为止,这是我的代码,但似乎wait(NULL)没有按预期工作。我不确定我做错了什么 #include <stdio.h> #include <sys/wait.h> #include <unistd.h> int main() { for (int i=0; i&

我有一个任务,我们应该创建特定数量的子进程,比如说3个,让父进程等待每个子进程完成。我们还应该有一个所有进程都要写入的管道,这样一旦父进程完成等待,它就会使用管道输出所有子进程结果的总和

到目前为止,这是我的代码,但似乎
wait(NULL)
没有按预期工作。我不确定我做错了什么

#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>

int main() {
  for (int i=0; i<3; i++) {
    pid_t child = fork();
    if (child > 0) {
      printf("Child %d created\n", child);
      wait(NULL);
      printf("Child %d terminated\n", child);
    }
  }

  printf("Parent terminated\n");
  return 0;
}
#包括
#包括
#包括
int main(){
对于(int i=0;i 0){
printf(“已创建子项%d”,子项);
等待(空);
printf(“已终止的子项%d\n”,子项);
}
}
printf(“母公司终止”);
返回0;
}

首先,最好先运行所有子进程,然后等待所有子进程,而不是依次等待每个子进程

此外,子进程应该立即退出,而不是继续运行分叉代码

第三,您必须注意并等待循环后的所有子项,而不仅仅是第一个终止的子项:

#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>

int main() {
  for (int i=0; i<3; i++) {
    pid_t child = fork();
    if (child > 0) {
      printf("Child %d created\n", child);
    }
    else if (child == 0) {
      printf("In child %d. Bye bye\n", i);
      return 0; // exit the child process
    }
  }

  while (wait(NULL) > 0); // wait for all child processes

  printf("Parent terminated\n");
  return 0;
}
#包括
#包括
#包括
int main(){
对于(int i=0;i 0){
printf(“已创建子项%d”,子项);
}
else if(子项==0){
printf(“在子项%d中,再见\n”,i);
返回0;//退出子进程
}
}
while(等待(NULL)>0);//等待所有子进程
printf(“母公司终止”);
返回0;
}
编辑:

上面的代码只是对问题中给出的示例的改进。为了实现从子进程到父进程的信息管道,可以创建一个管道(使用
pipe()
),并且可以从子进程访问写结束文件描述符


这是一个很好的例子。

在循环中,创建的第一个子项将继续进行下一次迭代,并调用“fork”,除非您“break”,而且,每个创建的子项(超过3个)都将写入“Parent terminated”。此外,如果您重定向或管程序的输出,以使其不是行缓冲的,那么您将看到您可能会考虑奇怪的行为。您可能需要添加else子句:
if(child>){…}else{{u exit(0);}
您已使父进程在创建其第一个子进程时立即等待。此外,子进程将继续创建自己的子进程(因为它在循环的中间分叉)等等。我闻到了递归的味道。这就是你被要求的吗?他们指定了子进程应该做什么吗?很有趣。因此,将
wait(NULL)
移出循环修复了它,但正如你们所说的,我似乎有3个以上的孩子。我做错了什么?我需要从父级而不是子级派生3个进程。如何停止递归?@williampersell请检查我的评论。我没有看到问题中提到的管道和求和。你挑了一些要点,但不是全部。嘿,谢谢,你说得对。我试图以代码为例并加以改进。没有关于信息pip的代码。这可以通过在父进程中创建管道(使用
pipe()
)来实现,子进程可以访问写入结束文件描述符,并且可以将信息写入管道。我将添加一个示例的链接。