<分区>
我正在用 fork()
和 pipe()
编写一个程序,使子进程写入管道,父进程读取(使用 getline ()
) 来自管道。但是如果不关闭父进程中的 pipe[1]
,getline()
就会永远挂起。为什么会这样?
我使用的是 Ubuntu 18.04 LTS。我阅读了手册,但它没有提到为什么 getline()
可能会卡在那里。
我的程序的一个简单的错误版本:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main() {
int fd[2];
char *s = NULL;
size_t n = 0;
int rt;
pipe(fd);
pid_t pid = fork();
if (pid != 0) {
//close(fd[1]); // without this line, getline() hangs
dup2(fd[0], STDIN_FILENO);
close(fd[0]);
while ((rt = getline(&s, &n, stdin)) != -1) {
printf("rt: %d\n", rt);
}
} else {
close(fd[0]);
dup2(fd[1], STDOUT_FILENO);
close(fd[1]);
for (int i = 0; i < 10; ++i) {
printf("aaa\n");
}
}
return 0;
}