热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

分叉的最后一个孩子不会死-Lastchildforkedwillnotdie

Ihavethemainprocessforkingtwotimesandthuscreatingtwochildren.Thetwochildrenarepiped

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).

删除一个wait()调用会显示ls |的预期结果更多,但给出了一些更奇怪的行为(卡住终端等)。

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;
}

2 个解决方案

#1


6  

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 from read()), and keeps waiting for more input.

在所有用户关闭写入结束之前,管道的读取端将不会获得EOF标记。两个孩子的父母仍然打开管道的两端,所以更多的人看不到EOF(从read()返回0),并且一直等待更多的输入。

#2


0  

Check with ps axw that it's really the more that isn't dying. Then read the man page for wait. Look at the returned status for wait.

用ps axw检查它真的不会死亡。然后阅读手册页等待。查看返回的等待状态。

(Hint: look at what causes a 'zombie' process. I don't think the waits are doing what you think they are.)

(提示:看看导致'僵尸'过程的原因。我不认为等待正在按照你的想法行事。)


推荐阅读
author-avatar
也许_枉然
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有