Hi,

I must be doing something really silly but it seems waitpid ends up
returning -1 if WNOHANG is specified and there are no children to
reap.

Am I doing something wrong ?

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

#include <err.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

void    reap_children(void);

sig_atomic_t gotchild;

void
childhandler(int signo)
{
        gotchild = 1;
}

void
reap_children(void)
{
        pid_t pid;
        int status;
        
        while ((pid = waitpid(WAIT_ANY, &status, WNOHANG)) > 0) {
                printf("Children %d reaped, terminated on ", pid);
                if (WIFEXITED(status))
                        printf("exit(%d)", WEXITSTATUS(status));
                if (WIFSIGNALED(status))
                        printf("signal %d", WTERMSIG(status));
                printf("\n");
        };
        
        if (pid == -1)
                err(1, "waitpid");
                
        gotchild = 0;
}

int
main(void)
{
        pid_t pid;
        
        signal(SIGCHLD, childhandler);

        if ((pid = fork()) == -1)
                err(1, "fork");
        if (pid == 0)           /* exit child */
                exit(1);
        if ((pid = fork()) == -1)
                err(1, "fork");
        if (pid == 0)           /* exit child */
                exit(1);

        for (;;) {
                if (gotchild)
                        reap_children();
                sleep(1);
        }
}

Here is the output:
Children 3318 reaped, terminated on exit(1)
Children 11320 reaped, terminated on exit(1)
waitpid: waitpid: No child processes

Reply via email to