7th May 2011

UNIX Programming Reference

Avoiding zombies when forking child processes

If the use case allows it, use wait(2) in a straightforward manner.

If exit status can be discarded, explicitly ignoring SIGCHLD is sufficient:

#include <signal.h>

int
main(int argc, char *argv[]) {
       signal(SIGCHLD, SIG_IGN);
}

If exit status is significant:

#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>

int have_zombies;

void
handle_sigchld() {
        have_zombies = 1;
}

void
reap_all_zombies() {
        int status;

        have_zombies = 0;
        while (waitpid(-1, &status, WNOHANG) > 0) {
                /* handle status */
        }
}

int
main(int argc, char *argv[]) {
        have_zombies = 0;
        signal(SIGCHLD, handle_sigchld);

        for (;;) {
                if (have_zombies) {
                        reap_all_zombies();
                }

                /* rest of main loop, including fork */
        }
}

IPv6/IPv6 independent BSD sockets

References:

Portability

References:


Back to Knowledge Base.

Ƿ