在 C 中 fork wait 和 pipe
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;
}
首先,最好先运行所有child个进程,然后等待所有进程,而不是依次等待每个进程。
此外,child 进程应该立即退出,而不是保留 运行ning 分叉代码。
第三,你必须注意并等待循环后的所有children,而不仅仅是第一个终止的:
#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;
}
编辑:
上面的代码只是对问题中给出的例子的改进。为了实现从 child 进程到 parent 的信息管道,可以创建一个管道(使用 pipe()
)并且 write-end 文件描述符可以从child 个进程。
Here's 一个很好的例子。
我有这个任务,我们应该创建特定数量的子进程,比方说 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;
}
首先,最好先运行所有child个进程,然后等待所有进程,而不是依次等待每个进程。
此外,child 进程应该立即退出,而不是保留 运行ning 分叉代码。
第三,你必须注意并等待循环后的所有children,而不仅仅是第一个终止的:
#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;
}
编辑:
上面的代码只是对问题中给出的例子的改进。为了实现从 child 进程到 parent 的信息管道,可以创建一个管道(使用 pipe()
)并且 write-end 文件描述符可以从child 个进程。
Here's 一个很好的例子。