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

发布于 2024-12-11 14:51:55 字数 851 浏览 0 评论 0原文

我的主进程分叉了两次,从而创建了两个子进程。两个孩子这样互相沟通:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

兮颜 2024-12-18 14:51:55

在所有用户关闭管道的写入端之前,管道的读取端不会获得 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 from read()), and keeps waiting for more input.

可可 2024-12-18 14:51:55

检查一下 ps axw 是否真的是 more 没有消亡。然后阅读 wait 的手册页。查看 wait 返回的状态。

(提示:看看是什么导致了“僵尸”进程。我认为等待并没有按照您的想法进行。)

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.

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文