Search code examples
cunixprocessforkparent

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


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


Solution

  • 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;
        }
    }