Course contentsShow
← C
Lesson 1077 of 1,21915. Systems ProgrammingFree lesson

Capturing child exit status

Capturing child exit status

What you'll learn: How to use the wait() function and status macros to find out if a child process finished successfully or crashed.

The "Return Receipt" analogy

When a parent process creates a child using fork(), it’s like sending a teenager out to run an errand. As a parent, you don't just want to know that they are home; you want to know how the errand went. Did they finish the task successfully? Did they run out of gas? Or did they quit halfway through?

In C, when a child process finishes, it doesn't just vanish. It turns into a "zombie" process, holding onto its exit code until the parent acknowledges it. The wait() function acts as the hand-off, where the parent collects the child's final report card.

Using wait() and macros

To capture the exit status, we pass an integer pointer to the wait() function. The operating system fills this integer with a encoded bitmask. We then use macros (special built-in functions) to decode that bitmask into human-readable information.

The two most important macros are:

  1. WIFEXITED(status): Returns true if the child terminated normally (e.g., return 0 or exit()).
  2. WEXITSTATUS(status): Extracts the actual return value (the 0 or 1) from the child.

Implementation

Here is how you catch that status in code:

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

int main() {
    pid_t pid = fork();

    if (pid == 0) {
        // The child process
        printf("Child: Doing work...\n");
        sleep(1);
        exit(42); // Exit with a specific status code
    } else {
        // The parent process
        int status;
        wait(&status); // Wait for child and catch the status

        if (WIFEXITED(status)) {
            int exit_code = WEXITSTATUS(status);
            printf("Parent: Child finished with code %d\n", exit_code);
        } else {
            printf("Parent: Child did not terminate normally.\n");
        }
    }
    return 0;
}

Why this matters

Checking the exit status is the only way to ensure your system is reliable. If your child process was supposed to save a file but crashed instead, your parent process needs to know so it can retry the operation or alert the user. Without wait() and its status macros, your parent process is essentially "flying blind," assuming everything went well when it might have failed.

Key takeaway

Use wait(&status) to collect a child's exit info, then use WIFEXITED and WEXITSTATUS to decode how the child finished.