Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
762 views
in Technique[技术] by (71.8m points)

c - wait for children and grand-children

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
", info->si_pid);
    pid_t pid = waitpid(-1, &exit_code, 0);
    if (pid == -1) {
        perror("waitpid()
");
    } else {
        printf("waitpid returned %d
", pid);
    }
    // set run = 0 when all children exit

    printf("end of sigchild handler
");
}

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
", getpid());
            exit (0);
        }
        sleep(1);
        printf ("son exit: %d
", getpid());
        exit (0);
    }

    while(run)
        sleep(1);

    printf("ciao
");
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...