【发布时间】:2018-03-09 10:54:26
【问题描述】:
我很难理解以下代码的行为。关闭文件描述符 p[0] 使程序退出(否则父进程将永远等待子进程)。这对我来说没有意义,因为子进程正在运行一个无限的while循环,为什么它们会因为管道的读取端关闭而退出?当然,您将无法写入管道,但 while 循环不依赖于父进程的读取端是否打开。我尝试删除子进程中的exit()函数,程序还是退出了,为什么子进程一发现读端关闭就杀死自己?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
main()
{
int run=10, fd[2]; pipe(fd); srand(time(0)); char ch, x='x', o='o';
if(!fork())
{
close(fd[0]);
while(run)
{
sleep(1+rand()%6); write(fd[1],&x,1);
}
exit(0); //This exit doesn't happen
}
if(!fork())
{
close(fd[0]);
while(run)
{
sleep(1+rand()%3); write(fd[1],&o,1);
}
exit(0); //This exit doesn't happen
}
close(fd[1]);
while(run--)
{
read(fd[0],&ch,1);
printf("%d %c\n",run,ch);
sleep(1);
}
close(fd[0]); //closing this file descriptor results in that the program can exit
wait(0);
wait(0);
exit(0);
}
【问题讨论】:
-
您确定您的应用程序可以在不添加我的答案中提到的头文件的情况下工作吗? (
)