wait(2)

โœจ wait(2) โœจ โ€” the System Calls Manual glow-up ๐Ÿ’…

okay bestie, sit DOWN, because this is the wait(2) page โ€” that's the manual name, that's the vibe โ€” and it's a whole โœจjourneyโœจ. We're talking wait, waitpid, waitid: the trio that lets a parent process sit there like ๐Ÿ‘€ waiting for its children to do literally anything.


๐ŸŽ€ NAME ๐ŸŽ€

wait, waitpid, waitid โ€” wait for process to change state

๐Ÿ“š LIBRARY ๐Ÿ“š

Standard C library (libc, -lc)

๐Ÿฆ‹ SYNOPSIS ๐Ÿฆ‹

#include <sys/wait.h>

pid_t wait(int *_Nullable wstatus);
pid_t waitpid(pid_t pid, int *_Nullable wstatus, int options);

int waitid(idtype_t idtype, id_t id, siginfo_t *infop, int options);
                /* This is the glibc and POSIX interface; see
                   VERSIONS for information on the raw system call.  */

๐Ÿงš Feature Test Macro Requirements for glibc (see feature_test_macros(7)) ๐Ÿงš

waitid():
    Since glibc 2.26:
        _XOPEN_SOURCE >= 500 || _POSIX_C_SOURCE >= 200809L
    glibc 2.25 and earlier:
        _XOPEN_SOURCE
            || /* Since glibc 2.12: */ _POSIX_C_SOURCE >= 200809L
            || /* glibc <= 2.19: */ _BSD_SOURCE

yeah so waitid() has โœจopinionsโœจ about which macros you define, depending on your glibc. Classic.


๐Ÿ’– DESCRIPTION ๐Ÿ’–

so. All of these system calls do the same main-character job: they wait for a state change in a child of the calling process, and then hand you the deets about which child changed state. ๐Ÿ’ซ

And what counts as a "state change", you ask? Three things, periodt:

  • the child terminated
  • the child was stopped by a signal
  • the child was resumed by a signal

If the child terminated, doing a wait also lets the system release all the resources tied to that child. ๐Ÿ‘‘ And if you don't wait? That terminated child just... stays there. In a "zombie" state. (see NOTES below โ€” yes, actual zombies, we'll get to it ๐Ÿ™ˆ).

If a child has already changed state, these calls come back immediately, no waiting, no drama. Otherwise they block until either a child changes state, or a signal handler interrupts the call โ€” assuming system calls aren't being auto-restarted via the SA_RESTART flag of sigaction(2). iykyk.

And for the rest of this page, a child whose state has changed and that nobody has waited on yet with one of these calls is called waitable. That's the technical term. We love a definition. ๐Ÿ’…

๐ŸŒธ wait() and waitpid() ๐ŸŒธ

wait() suspends execution of the calling thread until one of its children terminates. And the call wait(&wstatus)? That's literally equivalent to:

waitpid(-1, &wstatus, 0);

waitpid() suspends execution of the calling thread until a child specified by the pid argument has changed state. By default waitpid() only waits for terminated children, but you can change that behaviour with the options argument, as described below. ๐Ÿ‘‡

The value of pid can be:

  • < -1 โ€” meaning wait for any child process whose process group ID is equal to the absolute value of pid.
  • -1 โ€” meaning wait for any child process.
  • 0 โ€” meaning wait for any child process whose process group ID is equal to that of the calling process at the time of the call to waitpid().
  • > 0 โ€” meaning wait for the child whose process ID is equal to the value of pid.

The value of options is an OR of zero or more of these constants:

  • WNOHANG โ€” return immediately if no child has exited.
  • WUNTRACED โ€” also return if a child has stopped (but not traced via ptrace(2)). Status for traced children which have stopped is provided even if this option is not specified.
  • WCONTINUED (since Linux 2.6.10) โ€” also return if a stopped child has been resumed by delivery of SIGCONT.

(For Linux-only options, see below.) ๐Ÿ‘€

If wstatus is not NULL, wait() and waitpid() store status information in the int it points to. And you inspect that integer with these macros โ€” and bestie, listen CLOSELY, because this trips everyone up: the macros take the integer itself as an argument, NOT a pointer to it, unlike what you do in wait() and waitpid()! ๐Ÿ˜ญ

  • WIFEXITED(wstatus) โ€” returns true if the child terminated normally, that is, by calling exit(3) or _exit(3), or by returning from main().
  • WEXITSTATUS(wstatus) โ€” returns the exit status of the child. This consists of the least significant 8 bits of the status argument that the child specified in a call to exit(3) or _exit(3), or as the argument for a return statement in main(). Only use this macro if WIFEXITED returned true. โš ๏ธ
  • WIFSIGNALED(wstatus) โ€” returns true if the child process was terminated by a signal.
  • WTERMSIG(wstatus) โ€” returns the number of the signal that caused the child process to terminate. Only use this macro if WIFSIGNALED returned true. โš ๏ธ
  • WCOREDUMP(wstatus) // POSIX.1-2024 โ€” returns true if the child produced a core dump (see core(5)). Only use this macro if WIFSIGNALED returned true. โš ๏ธ
  • WIFSTOPPED(wstatus) // POSIX.1-2024 โ€” returns true if the child process was stopped by delivery of a signal; this is possible only if the call was done using WUNTRACED or when the child is being traced (see ptrace(2)).
  • WSTOPSIG(wstatus) โ€” returns the number of the signal which caused the child to stop. Only use this macro if WIFSTOPPED returned true. โš ๏ธ
  • WIFCONTINUED(wstatus) โ€” (since Linux 2.6.10) returns true if the child process was resumed by delivery of SIGCONT.

๐ŸŒˆ waitid() ๐ŸŒˆ

The waitid() system call โ€” available since Linux 2.6.9 โ€” gives you way more precise control over which child state change you're waiting for. Fancy. ๐Ÿ’…

The idtype and id arguments select the child(ren) to wait for, like this:

  • idtype == P_PID โ€” Wait for the child whose process ID matches id.
  • idtype == P_PIDFD (since Linux 5.4) โ€” Wait for the child referred to by the PID file descriptor specified in id. (See pidfd_open(2) for further information on PID file descriptors.)
  • idtype == P_PGID โ€” Wait for any child whose process group ID matches id. Since Linux 5.4, if id is zero, then wait for any child that is in the same process group as the caller's process group at the time of the call.
  • idtype == P_ALL โ€” Wait for any child; id is ignored.

The child state changes to wait for are specified by ORing one or more of these flags into options:

  • WEXITED โ€” Wait for children that have terminated.
  • WSTOPPED โ€” Wait for children that have been stopped by delivery of a signal.
  • WCONTINUED โ€” Wait for (previously stopped) children that have been resumed by delivery of SIGCONT.

And you can additionally OR these flags into options too:

  • WNOHANG โ€” As for waitpid().
  • WNOWAIT โ€” Leave the child in a waitable state; a later wait call can be used to again retrieve the child status information.

On a successful return, waitid() fills in these fields of the siginfo_t structure pointed to by infop:

  • si_pid โ€” The process ID of the child.
  • si_uid โ€” The real user ID of the child. (This field is not set on most other implementations.)
  • si_signo โ€” Always set to SIGCHLD.
  • si_status โ€” Either the exit status of the child, as given to _exit(3) (or exit(3)), or the signal that caused the child to terminate, stop, or continue. The si_code field can be used to determine how to interpret this field.
  • si_code โ€” Set to one of: CLD_EXITED (child called _exit(3)); CLD_KILLED (child killed by signal); CLD_DUMPED (child killed by signal, and dumped core); CLD_STOPPED (child stopped by signal); CLD_TRAPPED (traced child has trapped); or CLD_CONTINUED (child continued by SIGCONT).

Now here's a lil gotcha ๐Ÿซถ: if WNOHANG was specified in options and there were no children in a waitable state, then waitid() returns 0 immediately, and the state of the siginfo_t structure pointed to by infop depends on the implementation. So to portably tell that case apart from the case where a child was waitable, zero out the si_pid field before the call, and check for a nonzero value in that field after the call returns. That's the move. ๐Ÿ’…

And then: POSIX.1-2008 Technical Corrigendum 1 (2013) adds the requirement that when WNOHANG is specified in options and there were no children in a waitable state, then waitid() should zero out the si_pid and si_signo fields of the structure. On Linux and other implementations that adhere to this requirement, it is not necessary to zero out the si_pid field before calling waitid(). However โ€” and this is the important part โ€” not all implementations follow the POSIX.1 specification on this point. ๐Ÿ™ˆ So don't get cocky.


๐Ÿ‘‘ RETURN VALUE ๐Ÿ‘‘

  • wait() โ€” on success, returns the process ID of the terminated child; on failure, -1 is returned.
  • waitpid() โ€” on success, returns the process ID of the child whose state has changed; if WNOHANG was specified and one or more child(ren) specified by pid exist, but have not yet changed state, then 0 is returned. On failure, -1 is returned.
  • waitid() โ€” returns 0 on success or if WNOHANG was specified and no child(ren) specified by id has yet changed state; on failure, -1 is returned.

On failure, each of these calls sets errno to indicate the error. ๐Ÿ“Œ


๐Ÿ’€ ERRORS ๐Ÿ’€

  • EAGAIN โ€” The PID file descriptor specified in id is nonblocking and the process that it refers to has not terminated.
  • ECHILD โ€” (for wait()) The calling process does not have any unwaited-for children.
  • ECHILD โ€” (for waitpid() or waitid()) The process specified by pid (waitpid()) or idtype and id (waitid()) does not exist or is not a child of the calling process. (This can happen for one's own child if the action for SIGCHLD is set to SIG_IGN. See also the Linux Notes section about threads.)
  • EINTR โ€” WNOHANG was not set and an unblocked signal or a SIGCHLD was caught; see signal(7).
  • EINVAL โ€” The options argument was invalid.
  • ESRCH โ€” (for wait() or waitpid()) pid is equal to INT_MIN.

๐Ÿฆ„ VERSIONS ๐Ÿฆ„

๐Ÿ’œ C library/kernel differences ๐Ÿ’œ

wait() is actually a library function that (in glibc) is implemented as a call to wait4(2). plot twist ๐Ÿซข

On some architectures, there is no waitpid() system call at all; instead, this interface is implemented via a C library wrapper function that calls wait4(2). the more you know ๐ŸŒˆ

And the raw waitid() system call takes a fifth argument, of type struct rusage *. If this argument is non-NULL, then it's used to return resource usage information about the child, in the same manner as wait4(2). See getrusage(2) for details.


โญ STANDARDS โญ

POSIX.1-2024.


๐Ÿ“œ HISTORY ๐Ÿ“œ

SVr4, 4.3BSD, POSIX.1-2001.


bestie we are SO not done ๐Ÿ’… part 2 is loadingโ€ฆ ๐ŸŽ€

๐ŸงŸ NOTES

okay so, listen up bestie, because this part is lowkey the most important lore drop of the whole page ๐Ÿ’€

When a child terminates but nobody has waited for it yet, it becomes a "zombie". Yes, literally called that. The kernel keeps a minimal little info packet about the zombie process โ€” its PID, its termination status, and its resource usage information โ€” so that the parent can still come along later and perform a wait to get the deets about the child. ๐ŸงŸโ€โ™€๏ธ

But here's the catch: as long as a zombie is not removed from the system via a wait, it will consume a slot in the kernel process table. And if that table fills up? You literally cannot create any more processes. Not it. So handle your zombies, bestie.

If a parent process terminates first, then its "zombie" children (if there are any) get adopted by init(1), or by the nearest "subreaper" process as defined through the use of the prctl(2) PR_SET_CHILD_SUBREAPER operation. And init(1) automatically performs a wait to remove the zombies. She's a real one for that. ๐Ÿซถ

Now, POSIX.1-2001 specifies that if the disposition of SIGCHLD is set to SIG_IGN, or the SA_NOCLDWAIT flag is set for SIGCHLD (see sigaction(2)), then children that terminate do not become zombies, and a call to wait() or waitpid() will block until all children have terminated, and then fail with errno set to ECHILD. โœจ

The original POSIX standard left the behavior of setting SIGCHLD to SIG_IGN unspecified. And ngl, there's a sneaky lil detail here: even though the default disposition of SIGCHLD is "ignore", explicitly setting the disposition to SIG_IGN results in different treatment of zombie process children. iykyk. ๐Ÿ‘€

Linux 2.6 conforms to the POSIX requirements. However, Linux 2.4 (and earlier) does not: if a wait() or waitpid() call is made while SIGCHLD is being ignored, the call behaves just as though SIGCHLD were not being ignored โ€” that is, the call blocks until the next child terminates and then returns the process ID and status of that child.

๐Ÿ’ป Linux notes

In the Linux kernel, a kernel-scheduled thread is not a distinct construct from a process. Plot twist! A thread is simply a process that is created using the Linux-unique clone(2) system call. Other routines such as the portable pthread_create(3) call are implemented using clone(2).

Before Linux 2.4, a thread was just a special case of a process, and as a consequence one thread could not wait on the children of another thread, even when the latter belongs to the same thread group. However, POSIX prescribes such functionality, and since Linux 2.4 a thread can, and by default will, wait on children of other threads in the same thread group. slay ๐Ÿ’…

The following Linux-specific options are for use with children created using clone(2); they can also, since Linux 4.7, be used with waitid():

  • __WCLONE โ€” wait for "clone" children only. If omitted, then wait for "non-clone" children only. (A "clone" child is one which delivers no signal, or a signal other than SIGCHLD to its parent upon termination.) This option is ignored if __WALL is also specified.
  • __WALL (since Linux 2.4) โ€” wait for all children, regardless of type ("clone" or "non-clone"). ๐ŸŒˆ
  • __WNOTHREAD (since Linux 2.4) โ€” do not wait for children of other threads in the same thread group. This was the default before Linux 2.4.

Since Linux 4.7, the __WALL flag is automatically implied if the child is being ptraced.


๐Ÿ› BUGS

Okay so according to POSIX.1-2008, an application calling waitid() must ensure that infop points to a siginfo_t structure (i.e., that it is a non-null pointer).

On Linux, if infop is NULL, waitid() succeeds, and returns the process ID of the waited-for child. ๐Ÿ˜ญ

Applications should avoid relying on this inconsistent, nonstandard, and unnecessary feature. fr fr, don't do it, bestie. It's giving "undefined behavior's chaotic cousin". ๐Ÿ’€

โœจ EXAMPLES

The following program demonstrates the use of fork(2) and waitpid(). The program creates a child process. Here's how it goes down:

  • If no command-line argument is supplied to the program, then the child suspends its execution using pause(2), to allow the user to send signals to the child. Chill mode. ๐Ÿ˜Œ
  • Otherwise, if a command-line argument is supplied, then the child exits immediately, using the integer supplied on the command line as the exit status.
  • The parent process executes a loop that monitors the child using waitpid(), and uses the W*() macros described above to analyze the wait status value. Main character energy, honestly. ๐Ÿ‘‘

The following shell session demonstrates the use of the program:

$ ./a.out &
Child PID is 32360
[1] 32359
$ kill -STOP 32360
stopped by signal 19
$ kill -CONT 32360
continued
$ kill -TERM 32360
killed by signal 15
[1]+  Done                    ./a.out
$

๐Ÿ“ Program source

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

int
main(int argc, char *argv[])
{
    int    wstatus;
    pid_t  cpid, w;

    cpid = fork();
    if (cpid == -1) {
        perror("fork");
        exit(EXIT_FAILURE);
    }

    if (cpid == 0) {            /* Code executed by child */
        printf("Child PID is %jd\n", (intmax_t) getpid());
        if (argc == 1)
            pause();                    /* Wait for signals */
        _exit(atoi(argv[1]));

    } else {                    /* Code executed by parent */
        do {
            w = waitpid(cpid, &wstatus, WUNTRACED | WCONTINUED);
            if (w == -1) {
                perror("waitpid");
                exit(EXIT_FAILURE);
            }

            if (WIFEXITED(wstatus)) {
                printf("exited, status=%d\n", WEXITSTATUS(wstatus));
            } else if (WIFSIGNALED(wstatus)) {
                printf("killed by signal %d\n", WTERMSIG(wstatus));
            } else if (WIFSTOPPED(wstatus)) {
                printf("stopped by signal %d\n", WSTOPSIG(wstatus));
            } else if (WIFCONTINUED(wstatus)) {
                printf("continued\n");
            }
        } while (!WIFEXITED(wstatus) && !WIFSIGNALED(wstatus));
        exit(EXIT_SUCCESS);
    }
}

๐Ÿ‘€ SEE ALSO

go read these next, bestie, I promise they're worth it ๐Ÿซถ


and that's the whole page, bestie!! you made it to the end, I'm so proud of you ๐Ÿฅน๐Ÿ’– this one's from Linux man-pages 6.20, dated 2026-06-05 โ€” go forth and reap your zombies (metaphorically. please. ๐ŸŒธ)

๐Ÿ“ฆ where this page comes from
  • arch rolling: man-pages 6.20-1 ยท BSD-2-Clause AND BSD-3-Clause AND BSD-4.3TAHOE AND BSD-4-Clause-UC AND GPL-1.0-or-later AND GPL-2.0-only AND GPL-2.0-or-later AND GPL-3.0-or-later AND LGPL-3.0-linking-exception AND LGPL-3.0-or-later AND LicenseRef-Public-Domain AND LicenseRef-UltraPermissive AND Linux-man-pages-1-para AND Linux-man-pages-copyleft AND Linux-man-pages-copyleft-2-para AND Linux-man-pages-copyleft-var AND MIT AND Spencer-94
  • nixpkgs unstable: man-pages 6.20
  • ๐Ÿ“œ the page's license: Linux-man-pages-copyleft
  • ๐Ÿ’– girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms