【发布时间】:2019-04-15 13:45:23
【问题描述】:
我正在编写一个带有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;
}
【问题讨论】: