【发布时间】:2021-03-18 15:17:16
【问题描述】:
我目前正在做一个项目,我需要创建多个从不同管道读取的 fork,直到管道关闭。 这里的问题是,如果我创建了多个管道,即使我关闭了所有管道的两侧,孩子仍然会被卡在读取状态。
这是我的代码的简化版本,但存在相同问题:
#include <stdlib.h>
#include <unistd.h>
#define NB_PIPES 2
void read_write_pipe(int pipefd[2]) { //write what goes through is pipe until it closed
char buf;
close(pipefd[1]); //close the writing part of the tube
while (read(pipefd[0], &buf, 1) > 0)
write(1, &buf, 1);
close(pipefd[0]);
_exit(EXIT_SUCCESS);
}
int main(void)
{
int pipefd[NB_PIPES][2];
pid_t cpid;
for (int i = 0; i < NB_PIPES; i++) { //I create my pype
pipe(pipefd[i]);
}
for (int i = 0; i < NB_PIPES; i++) {
cpid = fork();
if (cpid == 0)
read_write_pipe(pipefd[i]); //create fork who will read from pipe i
else {
close(pipefd[i][0]); //close the reading part of pipe i
}
}
for (int i = 0; i < NB_PIPES; i++) {
write(pipefd[i][1], "Salut\n", 6); //write through pipe i
close(pipefd[i][1]); //close the writing part of pipe i
}
for (int i = 0; i < NB_PIPES; i++) {
wait(NULL);
}
return (0);
}
我用ggc编译
感谢您的阅读和帮助!
【问题讨论】:
-
当你先创建所有管道然后循环调用
fork时,所有进程中的所有管道都会打开,所以你必须关闭所有子进程中所有不相关的管道。 -
好的!非常感谢你 !它现在有效!我应该重新发布正确的代码以显示答案吗?
-
您可以为自己的问题添加答案。 (不要修改问题来回答它。)