等待孩子和孙子孙女 [英] wait for children and grand-children

查看:24
本文介绍了等待孩子和孙子孙女的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你怎么能等到所有的孩子和孙子都退出了,而不会在信号处理程序中阻塞?到目前为止,这是我的尝试.

How can you wait until all children and grand-children have exited, without blocking in a signal handler? This is my attempt so far.

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

int run = 1;

void handler(int sig, siginfo_t *info, void *uap)
{
    int exit_code;

    printf("sigchld pid %d\n", info->si_pid);
    pid_t pid = waitpid(-1, &exit_code, 0);
    if (pid == -1) {
        perror("waitpid()\n");
    } else {
        printf("waitpid returned %d\n", pid);
    }
    // set run = 0 when all children exit

    printf("end of sigchild handler\n");
}

void main() {

    struct sigaction chld;
    chld.sa_sigaction = handler;
    chld.sa_flags = SA_NOCLDSTOP | SA_SIGINFO;
    sigaction(SIGCHLD, &chld, NULL);

    //procmask sigchld?
    if (!fork ()) {
        if (!fork ()) {
            sleep(2);
            printf ("grand-son exit: %d\n", getpid());
            exit (0);
        }
        sleep(1);
        printf ("son exit: %d\n", getpid());
        exit (0);
    }

    while(run)
        sleep(1);

    printf("ciao\n");
}

推荐答案

虽然 SIGCHLD 和 waitpid 等确实只对直系子进程有效,但在 UNIX 系统上你经常可以作弊"" 有点继承资源从父级传递到子级到孙子级,并在进程终止时关闭.

While it is true that SIGCHLD and waitpid, etc., only work for immediate children, on UNIX systems you can often "cheat" a little bit with inherited resources passed from parent to child to grandchild, and closed upon process termination.

例如,原始进程可能会打开一个pipe,也许设置 read 结束 close-on-exec,让子孙继承写端.当原始进程准备好等待所有后代终止时,它关闭管道的写端并阻塞 reads 或 selects 以提高剩余描述符的可读性.当最后一个后代终止时,管道的读取端将传递一个 EOF.

For example, the original process might open a pipe, and perhaps set the read end of it close-on-exec, so that children and grandchildren inherit the write end. When the original process is ready to wait for all descendants to terminate, it closes its write end of the pipe and blockingly reads or selects for readability on the remaining descriptor. When the last descendant has terminated, the read end of the pipe will deliver an EOF.

不能保证这种策略 - 子代或孙代可能会谨慎关闭继承的文件描述符 - 但通常效果很好.

This tactic is not guaranteed — a child or grandchild might cautiously close inherited file descriptors — but it often works well enough.

这篇关于等待孩子和孙子孙女的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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