Skip to content
systemcoding.dev
Systems Programming

Wait for Child Processes with waitpid and Decode the Exit Status

Use waitpid in C on Linux to wait for a child, poll with WNOHANG, and decode the exit status with WIFEXITED, WEXITSTATUS and WTERMSIG.

7 min read
Summarize in AI
Flat illustration of user space above the system call boundary, the kernel and the hardware, with the C, FreeBSD and Linux logos.

When a child process ends, the kernel keeps a small record of how it ended until the parent asks. That request is waitpid, and the answer comes back as one integer that packs several facts into its bits. Reading it with == or / 256 works by accident on some systems and fails on others, so this post covers the portable way: the W macros in <sys/wait.h>. The examples use GCC 14 on Linux 6.12 with glibc 2.40, and the life cycle around them is in the complete guide to Unix processes.

The call is specified in POSIX.1-2024, and Linux adds details in the waitpid(2) man page.

The call and its return value

c
pid_t waitpid(pid_t pid, int *wstatus, int options);

The first argument chooses which children to wait for:

pidWaits for
greater than 0the child with exactly that process ID
-1any child
0any child in the caller's process group
less than -1any child in the process group -pid

On success waitpid returns the process ID of the child whose state changed. It returns 0 only when you passed WNOHANG and no child had changed state yet. It returns -1 on error, and the error you should expect is ECHILD, meaning there is no child left to wait for. wait(&status) is the same as waitpid(-1, &status, 0).

Wait for one child and decode how it ended

The status integer must be asked questions. This program starts one child that exits with a chosen code:

wait_one.cc
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>

int main(void)
{
    pid_t pid = fork();
    if (pid < 0) {
        perror("fork");
        return EXIT_FAILURE;
    }
    if (pid == 0)
        _exit(42);

    int status;
    pid_t done = waitpid(pid, &status, 0);
    if (done < 0) {
        perror("waitpid");
        return EXIT_FAILURE;
    }

    if (WIFEXITED(status))
        printf("child %d exited normally with code %d\n", (int)done, WEXITSTATUS(status));
    else if (WIFSIGNALED(status))
        printf("child %d was killed by signal %d\n", (int)done, WTERMSIG(status));
    return EXIT_SUCCESS;
}
Text
child 4021 exited normally with code 42

WIFEXITED(status) is true when the child called exit, _exit or returned from main, and then WEXITSTATUS(status) gives the code. Only the low eight bits of the code survive, so _exit(300) arrives as 44, which is 300 modulo 256. The process ID will differ on your machine.

A child killed by a signal has no exit code

When a signal ends a child, WIFEXITED is false and WIFSIGNALED is true. Calling WEXITSTATUS on such a status gives a meaningless number, so always test first. This program kills its child with a segmentation fault on purpose:

wait_signal.cc
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>

int main(void)
{
    pid_t pid = fork();
    if (pid < 0) {
        perror("fork");
        return EXIT_FAILURE;
    }
    if (pid == 0) {
        volatile int *p = NULL;
        *p = 1;
        _exit(0);
    }

    int status;
    waitpid(pid, &status, 0);

    if (WIFSIGNALED(status)) {
        int sig = WTERMSIG(status);
        printf("killed by signal %d (%s)%s\n", sig, strsignal(sig),
               WCOREDUMP(status) ? ", core dumped" : "");
    }
    return EXIT_SUCCESS;
}

On a system that writes core files, the output is:

Text
killed by signal 11 (Segmentation fault), core dumped

WCOREDUMP is not in POSIX, but glibc provides it. Whether a core file is really written depends on the RLIMIT_CORE limit and the system's core pattern, so the suffix may be absent on your machine. A shell reports this same death as exit status 139, which is 128 plus 11. That convention belongs to the shell, and a C program should read the signal directly.

Waiting for several children

A parent that starts several children has two choices. It can wait for each one in turn by process ID, which reports in start order, or it can wait for whichever finishes next with waitpid(-1, ...), which reports in finish order. The second is what a job runner wants:

wait_any.cc
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>

int main(void)
{
    unsigned delays[] = { 3, 1, 2 };

    for (int i = 0; i < 3; i++) {
        pid_t pid = fork();
        if (pid < 0) {
            perror("fork");
            return EXIT_FAILURE;
        }
        if (pid == 0) {
            sleep(delays[i]);
            _exit(i);
        }
    }

    int status;
    pid_t done;
    while ((done = waitpid(-1, &status, 0)) > 0)
        printf("child %d finished with code %d\n", (int)done, WEXITSTATUS(status));

    return EXIT_SUCCESS;
}

The child with code 1 sleeps one second, the one with code 2 sleeps two seconds, and the one with code 0 sleeps three, so the reports come out in finish order, not start order:

Text
child 5103 finished with code 1
child 5104 finished with code 2
child 5102 finished with code 0

The loop ends when waitpid returns -1. At that point errno is ECHILD, which is the normal sign that every child has been collected, not a failure. Treating that return as an error and printing a message is a common mistake.

Polling without blocking

Pass WNOHANG and waitpid returns immediately. A return of 0 means "children exist, none has finished yet". That lets a parent do other work in between checks:

wait_poll.cc
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>

int main(void)
{
    pid_t pid = fork();
    if (pid < 0) {
        perror("fork");
        return EXIT_FAILURE;
    }
    if (pid == 0) {
        sleep(2);
        _exit(0);
    }

    int ticks = 0;
    for (;;) {
        int status;
        pid_t r = waitpid(pid, &status, WNOHANG);
        if (r == pid) {
            printf("child done after %d checks\n", ticks);
            break;
        }
        if (r < 0) {
            perror("waitpid");
            return EXIT_FAILURE;
        }
        ticks++;
        usleep(500000);
    }
    return EXIT_SUCCESS;
}

With checks every half second and a two-second child, the parent sees four empty polls before it collects the child:

Text
child done after 4 checks

The count is approximate, because timing depends on the scheduler: it could be four or five. Polling in a loop is a simple way to learn the call, but it wastes wake-ups. For real programs, block in waitpid, handle SIGCHLD, or watch a pidfd with poll.

Why the status is one integer

The kernel packs the exit code into bits 8 to 15 of the status, the terminating signal into the low seven bits, and a core-dump flag into bit 7. The layout is an implementation detail that POSIX deliberately hides behind the macros, so code that shifts the integer by hand works on Linux today and breaks on a system with a different layout. Treat the integer as opaque, pass it to the macros, and log the decoded values rather than the raw number, which nobody can read at a glance.

Stopped and continued children

By default waitpid reports only children that ended. Pass WUNTRACED to also learn when a child is stopped by a signal such as SIGSTOP or Ctrl+Z, and WCONTINUED to learn when it resumes. These two matter to shells that manage jobs. The macros WIFSTOPPED, WSTOPSIG and WIFCONTINUED decode them.

The rule for all the macros is the same: ask which kind of event it is first, then read the value that belongs to that kind. Skipping the question is where wrong numbers come from.

CheckIf true, read
WIFEXITED(s)WEXITSTATUS(s)
WIFSIGNALED(s)WTERMSIG(s) and optionally WCOREDUMP(s)
WIFSTOPPED(s)WSTOPSIG(s)
WIFCONTINUED(s)nothing more

An interrupted wait

If a signal handler runs while waitpid is blocked, the call can fail with EINTR, depending on how the handler was installed. Install handlers with SA_RESTART so the call restarts by itself, or retry in a loop:

wait_retry.cc
#include <errno.h>
#include <sys/wait.h>

pid_t wait_retry(pid_t pid, int *status)
{
    pid_t r;
    do {
        r = waitpid(pid, status, 0);
    } while (r < 0 && errno == EINTR);
    return r;
}

This helper has no output; it is the standard shape for a blocking wait in code that handles signals. Only EINTR is retried. ECHILD and EINVAL are real errors that a retry cannot fix.

Where waitpid is not enough

waitpid blocks or polls, and it works on children only. You cannot wait for an unrelated process, and you cannot wait on several children together with a socket in one poll call. For the second need, Linux 5.3 added pidfd_open, which returns a descriptor that becomes readable when the process ends. For observing a process that is not your child, there is no portable equivalent; tools watch /proc or use ptrace. If your parent is a thread in a larger program, check the interplay with other code that calls wait(-1): a library that reaps every child will steal the statuses of the ones you started.

Share

Keep reading

Flat illustration of two options weighed side by side, with the macOS, Linux and Apple logos.
Kernels

Mach Traps vs BSD System Calls on macOS

Learn how macOS routes one trap instruction to either a Mach trap or a BSD system call, how the number sign and class decide, and why you should call libSystem.

8 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.