【问题标题】:Only one grandchild killed instead of 5只有一个孙子被杀而不是五个
【发布时间】:2016-04-25 13:48:47
【问题描述】:

这是我之前问题的从头开始编写的。我真正需要实现的是:在未来 parent 工作能够关闭 pipe 的一端,以便 grandchild ( daemon ) 将收到 SIGPIPE。当我使用 1 解决方案时,它就像一个魅力(但这是在任何分叉之前)。当我使用 2 解决方案时,只有一次写入会生成 SIGPIPE。我该如何检查?通过发出: strace -f ./a.out 2>&1 | grep 管道

#include <sys/wait.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>

void child_become_daemon( int pfd[][2], int id )
{
    int pid = fork();
    if( pid == 0 )
    {
        dup2( pfd[id][1], 1 );
        close( pfd[id][0] );
        sleep( 5 ); //this is to be sure that opposite end is already closed
        write( 1, "child", strlen( "child" ) );
    }
    if( pid > 0 )
    {
        exit( 0 );
    }
}

int main()
{
    int pid;
    int numKids = 5;
    int procNum;

    int pfd[numKids][2];
    for( int i = 0; i < numKids; ++i )
    {
        pipe( pfd[ i ] );
        //close( pfd[i][0] );//1 all killed - perfect
    }

    for( procNum = 0; procNum < numKids; procNum++ ) {
        pid = fork();
        if( pid == 0 ) {
            break;
        }
    }

    if( pid == 0 ) {
        printf( "I'm child %d\n", procNum );
        child_become_daemon( pfd, procNum );
    }
    else {
        for( int i = 0; i < numKids; ++i )
        {
            printf( "closing %d\n", i );
            close( pfd[i][0] );//2 why only one will get killed
            close( pfd[i][1] );
        }

        char buf[124] = { 0 };
        for( int i = 0; i < numKids; ++i )
        {
            read( pfd[i][0], buf, 124 );
            printf( "buf: %s\n", buf );
        }

         int p, status;
         while ((p = wait(&status)) != -1)
             fprintf(stderr, "p %d exits with %d\n", p, WEXITSTATUS(status));
    }

    return 0;
}

【问题讨论】:

    标签: c linux operating-system embedded


    【解决方案1】:

    孙子继承了所有 5 个管道,因此它们每个都打开了其他 4 个管道以供读取,因此没有 SIGPIPE。如果有一个“不幸”的时机,最后一个活着的人可能会得到一个 SIGPIPE,因为其余的人都没有了。

    [编辑] 你也没有办法真正知道,因为如果他们的父母已经死了,你不能等待孙子进程。而且您不会在孙辈中发现 SIGPIPE。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-21
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多