【发布时间】:2014-04-06 11:49:45
【问题描述】:
上面的代码没有给出任何警告或错误,但是父级没有打印通过管道传递的字符串。有什么想法吗?
pid_t pid;
int fd[2];
int num_bytes_read;
char buffer[80];
pipe (fd);
pid=fork();
if (pid == 0) {/*Son*/
fclose(stdout);
close(fd[0]);
dup(fd[1]);
printf ("write in pipe\n");
fflush(stdout);
}
else { /*Parent*/
close (fd[1]);
num_bytes_read = read (fd[0], buffer, sizeof (buffer));
printf ("The received string is: %s\n", buffer);
}
return (0);
【问题讨论】:
-
尝试使用
close(1);而不是fclose(stdout); -
仅供参考,这取决于您使用的 C 库 - 在 musl 上,它按原样工作。