最后一个分叉的孩子不会死
我的主进程分叉了两次,从而创建了两个子进程。两个孩子这样互相沟通:
ls | more
现在的问题是第二个孩子永远不会死。这是为什么?管道中的最后一个孩子什么时候真正死亡?
删除一个 wait() 调用会显示 ls | 的预期结果更多
但给出了一些进一步奇怪的行为(卡住终端等)。
这是我的代码:
int main(){
printf("[%d] main\n", getpid());
int pip[2], i;
pipe(pip);
/* CHILDREN*/
for (i=0; i<2; i++){
if (fork()==0){
/* First child */
if (i==0){
printf("[%d] child1\n", getpid());
close(1); dup(pip[1]);
close(pip[0]);
execlp("ls", "ls", NULL);}
/* Second child */
if (i==1){
printf("[%d] child2\n", getpid());
close(0); dup(pip[0]);
close(pip[1]);
execlp("more", "more", NULL);}
}
}
wait(NULL); // wait for first child
wait(NULL); // wait for second child
return 0;
}
I have the main process forking two times and thus creating two children. The two children are piped with each other like this:
ls | more
Now the problem is that the second child never dies. Why is that? When does the last child in a pipe die really?
Removing one wait() call shows the expected result of ls | more
but gives some further weird behaviours(stuck terminal etc).
Here is my code:
int main(){
printf("[%d] main\n", getpid());
int pip[2], i;
pipe(pip);
/* CHILDREN*/
for (i=0; i<2; i++){
if (fork()==0){
/* First child */
if (i==0){
printf("[%d] child1\n", getpid());
close(1); dup(pip[1]);
close(pip[0]);
execlp("ls", "ls", NULL);}
/* Second child */
if (i==1){
printf("[%d] child2\n", getpid());
close(0); dup(pip[0]);
close(pip[1]);
execlp("more", "more", NULL);}
}
}
wait(NULL); // wait for first child
wait(NULL); // wait for second child
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在所有用户关闭管道的写入端之前,管道的读取端不会获得 EOF 标记。两个子进程的父进程仍然打开管道的两端,因此
more
没有看到 EOF(从read()
返回 0),并继续等待以获得更多输入。The read end of the pipe won't get an EOF mark until the write end has been closed by all its users. The parent of both children still has both ends of the pipe open, so
more
doesn't see an EOF (a return of 0 fromread()
), and keeps waiting for more input.检查一下
ps axw
是否真的是more
没有消亡。然后阅读 wait 的手册页。查看wait
返回的状态。(提示:看看是什么导致了“僵尸”进程。我认为等待并没有按照您的想法进行。)
Check with
ps axw
that it's really themore
that isn't dying. Then read the man page for wait. Look at the returned status forwait
.(Hint: look at what causes a 'zombie' process. I don't think the waits are doing what you think they are.)