syscalls

wait4() — Linux system interface

Wait for a selected child state change, optionally retrieving resource usage. Select a positive PID for one child; -1 selects any child, 0 selects the caller’s process group, less than -1 selects a specified group. WNOHANG may return 0 without a report. Interpret termination with WIFEXITED/WEXITSTATUS or WIFSIGNALED, not raw status. EINTR can be retried; ECHILD means no eligible child. Waiting for a terminated child reaps it. Resource values vary by workload; do not treat them as benchmark results. Compile the complete C example in a fresh private working directory using gcc -std=c17 -Wall -Wextra -Wpedantic -Werror example.c -o example; run ./example. BSD-style non-POSIX extension; glibc exposes it with _DEFAULT_SOURCE. Prefer waitpid for portable status-only waiting. These are libc-facing signatures, not raw architecture-specific syscall ABIs.

Formal Syntax & Structure

linux syntaxlinux
#define _DEFAULT_SOURCE#include <sys/wait.h>#include <sys/resource.h>pid_t wait4(pid_t pid, int *wstatus, int options, struct rusage *rusage);

Parameters & Attributes

NameTypeDescription
pidpid_tChild or process-group selector.
wstatusint *Status output pointer; NULL to discard.
optionsint0 or supported wait flags.
rusagestruct rusage *Resource usage output pointer or NULL.

Return Value

pid_t

Reported child PID, or 0 with WNOHANG when no report is ready. On failure, returns -1 and sets errno.

Working Example

Example Snippetlinux
#define _DEFAULT_SOURCE#define _POSIX_C_SOURCE 200809L#include <errno.h>#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <sys/wait.h>#include <sys/resource.h>
/* A failed check ends this short-lived demonstration. */#define CHECK(x) do { if (!(x)) { \    fprintf(stderr, "check failed at line %d: %s\n", __LINE__, #x); \    return EXIT_FAILURE; \} } while (0)
int main(void){    pid_t child = fork();    CHECK(child >= 0);    if (child == 0) _exit(4);    int status;    struct rusage usage;    pid_t got;    do { got = wait4(child, &status, 0, &usage); } while (got < 0 && errno == EINTR);    CHECK(got == child && WIFEXITED(status) && WEXITSTATUS(status) == 4);    CHECK(usage.ru_utime.tv_sec >= 0 && usage.ru_stime.tv_sec >= 0);    CHECK(wait4(child, &status, WNOHANG, NULL) == -1 && errno == ECHILD);    puts("child exit=4; usage available; already reaped");    return EXIT_SUCCESS;}
Linux Reference