简体   繁体   English

为什么我的 while(read) 循环管道永远不会结束?

[英]Why does my while(read) loop with pipes never end?

// 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]);

I'm really baffled by these pipes.我真的被这些管道搞糊涂了。 fgets should read up to and including the newline. fgets应该读到并包括换行符。 It reads, and successfully prints "hello".它读取并成功打印“hello”。 However, the process doesn't end.然而,这个过程并没有结束。 I've closed the write end of the pipe of the parent.我已经关闭了父管道的写端。 So it should return 0 or EOF , and the while loop should exit.所以它应该返回 0 或EOF ,并且 while 循环应该退出。

I've tried different combinations of "hello" with and without the newline character and null-terminator.我尝试了不同的“hello”组合,有和没有换行符和空终止符。 I really don't see what the problem is.我真的不明白问题是什么。

In order to have fd[0] reach EOF you need to have closed fd[1] in all the processes who know them.为了让fd[0]到达EOF您需要在所有知道它们的进程中关闭fd[1] In your case you should close fd[1] in the child process right after the fork()在您的情况下,您应该在fork()之后立即关闭子进程中的fd[1]

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM