[英]Why do I get a close: Bad file descriptor error for this fork pipe c program?
int main(int argc, char ** argv) {
int count = 2;
int pid, status;
int fd[count][2];
int i;
for (i = 0; i < count; i++) {
if (pipe(fd[i]) != 0) {
perror("pipe");
exit(1);
}
pid = fork();
if (pid < 0) {
perror("fork");
exit(1);
} else if (pid == 0) {
if (close(fd[i][1]) != 0) {
perror("close");
exit(1);
}
int j;
for (j = 0; j < i; j++ ) {
close(fd[j][1]);
}
char w[MAXWORD];
int result;
result = read(fd[i][0], w, MAXWORD);
w[result-1] = '\0';
printf("child %s\n" w);
if (result == -1) {
perror("read");
exit(1);
}
exit(0);
} else {
if (close(fd[i][0]) != 0) {
perror("close");
exit(1);
}
}
}
while (1) {
char word[MAXWORD]; int c;
c = read(STDIN_FILENO, word, MAXWORD);
if (c == 0) {
break;
}
word[c-1] = '\0';
for (i = 0; i < count; i++ ) {
write(fd[i][1], word, strlen(word)+1);
}
for (i = 0; i < count; i++ ) {
if (close(fd[i][1]) != 0) {
perror("close");
exit(1);
}
}
for (i = 0; i < count; i++) {
wait(&status);
}
}
return 0;
}
我的代码在循环中读取用户输入的单词,直到按下control + d为止。 该单词被发送到两个子进程的管道。 他们两个都印字。 如果我取出while(1)陈述,则可以正常工作。 问题是当我保持while 1循环第二次输入单词时出现此错误:
$ query
hello
child hello
child hello
hello
close: Bad file descriptor
请我真的需要帮助,因为我真的不知道为什么要这么做。 谢谢。
几个问题
1)每个孩子只能阅读一次,然后回声,然后退出,但是您的while循环似乎想向每个孩子发送多个单词(尽管这不是导致问题的原因)
2)在主while循环中,您读取单词,将其写入每个孩子,然后关闭您写入的文件描述符。 第二次通过循环关闭所有描述符,因此close调用失败。 写调用也失败了,但是因为您不检查返回值,所以您没有意识到。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.