[英]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.