如何解决在 c 中关闭时的并行管道问题
我目前正在做一个项目,我需要创建多个从不同管道读取的叉子,直到管道关闭。 这里的问题是,如果我创建了多个管道,即使我关闭了所有管道的两侧,孩子仍然无法阅读。
这是我的代码的简化版本,但存在相同问题:
#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,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
编译
感谢阅读和帮助!
解决方法
所以感谢 Bodo 我发现了这个问题 这是代码的正确版本:
#include <stdlib.h>
#include <unistd.h>
#define NB_PIPES 2
void read_write_pipe(int pipefd[NB_PIPES][2],int i) { //write what goes through is pipe until it closed
char buf;
for (int j = 0; j < NB_PIPES; j++) {
if (j != i) {
close(pipefd[j][0]); //close all the other pipe
close(pipefd[j][1]);
}
}
close(pipefd[i][1]); //close the writing part of the tube
while (read(pipefd[i][0],&buf,1) > 0)
write(1,1);
close(pipefd[i][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
}
}
sleep(1);
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);
}
感谢您的帮助!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。