最后一个孩子分叉不会死 [英] Last child forked will not die

查看:211
本文介绍了最后一个孩子分叉不会死的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的主要过程分叉两次,从而创造两个孩子。两个孩子都通过管道相互是这样的:

  LS |更多

现在的问题是,第二个孩子永远不死。这是为什么?什么时候在管道的最后一个子死真的吗?

移除一个的等待()的来电显示 LS的预期结果|更多,但给出了一些进一步的怪异行为(卡终端等)。

下面是我的code:

  INT的main(){
  的printf([%D]。主要\\ n,GETPID());
  INT PIP [2],I;
  管(PIP);  / *儿童版* /
  对于(I = 0; I&2;我++){
    如果(叉()== 0){      / *第一个孩子* /
      如果(我== 0){
        的printf([%D]。child1 \\ n,GETPID());
        关闭(1); DUP(PIP [1]);
        关闭(PIP [0]);
        execlp(LS,LS,NULL);}      / *老二* /
      如果(ⅰ== 1){
        的printf([%d个]的child2 \\ n,GETPID());
        关闭(0); DUP(PIP [0]);
        关闭(PIP [1]);
        execlp(多,多,NULL);}
    }
  }
  等待(NULL); //等待第一个孩子
  等待(NULL); //等待第二个孩子
  返回0;
}


解决方案

管道,直到写端已经被它的所有用户关闭不会得到一个EOF标记的读端。两个孩子的家长仍有打开管道的两端,所以更多没有看到一个EOF(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;
}

解决方案

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.

这篇关于最后一个孩子分叉不会死的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆