Search code examples
linuxprocessforkwait

On linux, how to wait for multiple child processes?


The *nix wait() and wait_pid() works in demo programs where

(1) a father forks a child, wait for the child to exit

(2) and the wait function returns.

It's emphasized that, if father doesn't wait and keep running, children exits and will be "Zombies".

But the real world *nix programming is like

(1) I am writing a server program,

(2) the main process works to fork some child workers,

(3) and these child workers do some job and then exit.

Then question is, how do father process fork and wait for multiple children? Is there a convenient way to do this, or the design should be sth different?

Thanks.


Solution

  • three possibilities:

    1) Periodically check for dead children with waitpid. Ie now and again do:

        while (waitpid(-1, NULL, WNOHANG) > 0)
            continue;
    

    2) Cleanup in a signal handler

    /* SIGCHLD handler to reap dead child processes */
    static void grimReaper(int sig)
    {
        int savedErrno = errno;
        while (waitpid(-1, NULL, WNOHANG) > 0)
            continue;
        errno = savedErrno;
    }   
    int main(void) {
        ...
        struct sigaction sa;
        memset(&sa, 0, sizeof sa);
        sigemptyset(&sa.sa_mask);
        sa.sa_handler = grimReaper;
        if (sigaction(SIGCHLD, &sa, NULL) == -1)
            ...
    }       
    

    3) Make detached children by ignoring SIGCHLD in the parent:

    signal(SIGCHLD, SIG_IGN);