【问题标题】:Why does my while(read) loop with pipes never end?为什么我的带有管道的 while(read) 循环永远不会结束?
【发布时间】:2016-03-19 21:25:01
【问题描述】:
// Some initialization

// Child process
// stdin is redirected to fd[0]
while (fgets(someCharArray, sizeof(someCharArray), stdin) {
    printf("%s\n", someCharArray);
}

// Parent process
char greeting[50] = "hello\n\0";
write(fd[1], greeting, sizeof(greeting));
close(fd[1]);

我真的对这些管道感到困惑。 fgets 应该读到并包括换行符。它读取并成功打印“hello”。然而,这个过程并没有结束。我已经关闭了父管道的写入端。所以它应该返回 0 或 EOF,并且 while 循环应该退出。

我尝试了不同的“hello”组合,有和没有换行符和空终止符。我真的不明白问题是什么。

【问题讨论】:

  • 子进程中你也closefd[1]?
  • 请显示minimal complete and verifiable example。您可能没有关闭所有正确的 fd。所以我们需要看完整的代码。
  • @jdarthenay 我对此不确定。子进程实际上已经执行了另一个源文件。所以它没有fd。我曾尝试在 while 循环之前 close stdout ,但这没有意义。这是否意味着我需要将主程序中的fd 传递给子程序?
  • @jdarthenay 哦。即使我将孩子的stdout 重定向到fd[1],我也不知道我仍然需要关闭它。谢谢。

标签: c string while-loop pipe fgets


【解决方案1】:

为了让fd[0] 到达EOF,您需要在所有认识它们的进程中关闭fd[1]。 在您的情况下,您应该在 fork() 之后的子进程中关闭 fd[1]

if (fork() == 0)
{
    close(fd[1]);
    // ...
    // instructions for child process
    exit 0;
}

【讨论】:

    猜你喜欢
    • 2011-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-11
    • 1970-01-01
    • 1970-01-01
    • 2017-05-21
    相关资源
    最近更新 更多