【问题标题】:Why do I get a close: Bad file descriptor error for this fork pipe c program?为什么我会关闭:此 fork pipe c 程序的文件描述符错误?
【发布时间】:2013-03-19 05:57:47
【问题描述】:
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

我真的需要帮助,因为我真的不知道为什么会这样。谢谢。

【问题讨论】:

  • Bad File descriptor 的可能重复项
  • 我认为这不适用于我。我在 for 循环中传递 i 的两个值。
  • 这样的问题很多。也许一些细节发生了变化,但它们对我来说似乎都是重复的。我刚刚投了票。我们会看看我是否正确。
  • 这不是 'Bad file descriptor' 的重复...它是松散相关的,但不是重复的。

标签: c process fork pipe stdin


【解决方案1】:

几个问题

1) 每个孩子只读取一次,回显,然后退出,但您的 while 循环似乎想要向每个孩子发送多个单词(但这不是导致问题的原因)

2) 在主 while 循环中,您读取单词,将其写入每个孩子,然后关闭您写入的文件描述符。第二次通过循环时,所有描述符都已关闭,因此关闭调用失败。写调用也失败了,但是因为你没有检查返回值,所以你没有意识到。

【讨论】:

  • 对于 1) 你说每个孩子只读一次。如何让它多次阅读?对于 2) 我是否将 close 语句放在 while 循环之外?
  • 和写一样,读也必须循环(直到读失败)
  • 嗯,有道理。但是 2)我无法弄清楚,因为如果我省略了 close 语句,当我输入第二个单词时程序会停止运行。有什么建议吗?
  • 将 close 和 wait 语句移到 while 循环之外。找出某种指示“输入不足”以退出 while 循环的方法(eof 会起作用)。
  • 澄清一下 - 将 for 循环和 close 和 wait 语句移到 while 循环之外。
猜你喜欢
  • 1970-01-01
  • 2014-07-14
  • 2016-08-26
  • 2014-02-15
  • 2023-03-06
  • 2021-03-12
  • 2011-10-02
  • 1970-01-01
  • 2014-12-20
相关资源
最近更新 更多