[英]Fork wait and pipe in C
我有这个任务,我们应该创建特定数量的子进程,比如说 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;
}
首先,最好先运行所有子进程,然后等待所有子进程,而不是依次等待每个子进程。
此外,子进程应立即退出,不要继续运行分叉代码。
第三,您必须注意并等待循环后的所有子级,而不仅仅是第一个终止的子级:
#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;
}
编辑:
上面的代码只是对问题中给出的示例的改进。 为了实现从子进程到父进程的信息管道,可以创建一个管道(使用pipe()
)并且可以从子进程访问写端文件描述符。
这是一个很好的例子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.