Check whether Child Process has terminated in C on Unix without blocking

Viewed 535

I would like to check whether / when a child process has terminated in C on Unix. It's not supposed to be blocking, rather a short check in a loop. My code:

pid_t pid = fork();
if (pid > 0)
    // Parent Process
    while (1) {
        // Do a short check whether Child has already terminated if yes break the loop.
    // Ik that it's possible to use waitpid(pid, &status, 0) but that blocks the whole loop until the child has terminated 

    }
if (pid == 0)
    printf("child process born");
    exit(0);

Thx in advance

2 Answers

The third argument to waitpid is a set of flags. If you pass WNOHANG to this argument, the function will return immediately if no children have yet exited.

You can then check if waitpid returned 0. If so, no child exited and you wait and try again.

while (1) {
    pid_t rval = waitpid(pid, &status, WNOHANG);

    if (rval == -1) {
        perror("waitpid failed");
        exit(1);
    } else if (rval == 0) {
        sleep(1);
    } else {
        break;
    }
}

Traditional way is:

#include <errno.h>
#include <sys/types.h>
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>

int exist(pid_t pid) {
   return kill(pid, 0) > 0 || errno != ESRCH;
}
int main(int ac, char **av) {
    while (--ac > 0) {
        pid_t p = strtol(*++av, 0, 0);
        printf("%d %s\n", p, exist(p) ? "exists" : "doesn't exist");
    }
    return 0;
}

It doesn't care about parent : child relation (whereas wait derivatives do), and works even if you don't have permission to affect the process.

Related