WAIT(3POSIX)
๐ธ WAIT(3POSIX) ๐ธ
okay bestie, this is the POSIX Programmer's Manual page for wait and waitpid, and I need you to know right now that the Linux implementation of this interface may differ (so like, consult the corresponding Linux manual page for the tea on Linux behavior), or honestly the interface may not even be implemented on Linux. ๐
โจ PROLOG โจ
This manual page is part of the POSIX Programmer's Manual. The Linux implementation of this interface may differ (consult the corresponding Linux manual page for details of Linux behavior), or the interface may not be implemented on Linux.
๐ NAME ๐
wait, waitpid โ wait for a child process to stop or terminate
๐ SYNOPSIS ๐
#include <sys/wait.h>
pid_t wait(int *stat_loc);
pid_t waitpid(pid_t pid, int *stat_loc, int options);
๐ฆ DESCRIPTION ๐ฆ
So the wait() and waitpid() functions shall obtain status information (see Section 2.13, Status Information) pertaining to one of the caller's child processes. wait() grabs status info for process termination from any child process. waitpid() grabs status info for process termination, and optionally process stop and/or continue, from a specified subset of the child processes. it's giving selective, and we love that for it ๐
wait() shall cause the calling thread to become blocked until status information generated by child process termination is made available to the thread, or until delivery of a signal whose action is either to execute a signal-catching function or to terminate the process, or an error occurs. If termination status information is available prior to the call to wait(), return shall be immediate. And if termination status information is available for two or more child processes, the order in which their status is reported is unspecified โ so don't come for her about the order, she didn't promise that.
As described in Section 2.13, Status Information, the wait() and waitpid() functions consume the status information they obtain. yeah. consumed. gone. eaten. ate. ๐
The behavior when multiple threads are blocked in wait(), waitid(), or waitpid() is described in Section 2.13, Status Information.
waitpid() shall be equivalent to wait() if the pid argument is (pid_t)-1 and the options argument is 0. Otherwise, its behavior shall be modified by the values of the pid and options arguments.
The pid argument specifies a set of child processes for which status is requested. waitpid() shall only return the status of a child process from this set:
- If
pidis equal to(pid_t)-1, status is requested for any child process. In this respect,waitpid()is then equivalent towait(). - If
pidis greater than0, it specifies the process ID of a single child process for which status is requested. - If
pidis0, status is requested for any child process whose process group ID is equal to that of the calling process. - If
pidis less than(pid_t)-1, status is requested for any child process whose process group ID is equal to the absolute value ofpid.
The options argument is constructed from the bitwise-inclusive OR of zero or more of the following flags, defined in the <sys/wait.h> header:
WCONTINUEDโ thewaitpid()function shall report the status of any continued child process specified bypidwhose status has not been reported since it continued from a job control stop.WNOHANGโ thewaitpid()function shall not suspend execution of the calling thread if status is not immediately available for one of the child processes specified bypid. no waiting, bestie, she's busy ๐WUNTRACEDโ the status of any child processes specified bypidthat are stopped, and whose status has not yet been reported since they stopped, shall also be reported to the requesting process.
If wait() or waitpid() return because the status of a child process is available, these functions shall return a value equal to the process ID of the child process. In this case, if the value of the argument stat_loc is not a null pointer, information shall be stored in the location pointed to by stat_loc. The value stored at the location pointed to by stat_loc shall be 0 if and only if the status returned is from a terminated child process that terminated by one of the following means:
- The process returned
0frommain(). - The process called
_exit()orexit()with a status argument of0. - The process was terminated because the last thread in the process terminated.
Regardless of its value, this information may be interpreted using the following macros, which are defined in <sys/wait.h> and evaluate to integral expressions; the stat_val argument is the integer value pointed to by stat_loc. these macros are the whole entire point, ok, they're the main characters ๐
WIFEXITED(stat_val)โ evaluates to a non-zero value if status was returned for a child process that terminated normally.WEXITSTATUS(stat_val)โ if the value ofWIFEXITED(stat_val)is non-zero, this macro evaluates to the low-order 8 bits of the status argument that the child process passed to_exit()orexit(), or the value the child process returned frommain().WIFSIGNALED(stat_val)โ evaluates to a non-zero value if status was returned for a child process that terminated due to the receipt of a signal that was not caught (see<signal.h>).WTERMSIG(stat_val)โ if the value ofWIFSIGNALED(stat_val)is non-zero, this macro evaluates to the number of the signal that caused the termination of the child process.WIFSTOPPED(stat_val)โ evaluates to a non-zero value if status was returned for a child process that is currently stopped.WSTOPSIG(stat_val)โ if the value ofWIFSTOPPED(stat_val)is non-zero, this macro evaluates to the number of the signal that caused the child process to stop.WIFCONTINUED(stat_val)โ evaluates to a non-zero value if status was returned for a child process that has continued from a job control stop.
It is unspecified whether the status value returned by calls to wait() or waitpid() for processes created by posix_spawn() or posix_spawnp() can indicate a WIFSTOPPED(stat_val) before subsequent calls to wait() or waitpid() indicate WIFEXITED(stat_val) as the result of an error detected before the new process image starts executing.
It is unspecified whether the status value returned by calls to wait() or waitpid() for processes created by posix_spawn() or posix_spawnp() can indicate a WIFSIGNALED(stat_val) if a signal is sent to the parent's process group after posix_spawn() or posix_spawnp() is called.
If the information pointed to by stat_loc was stored by a call to waitpid() that specified the WUNTRACED flag and did not specify the WCONTINUED flag, exactly one of the macros WIFEXITED(*stat_loc), WIFSIGNALED(*stat_loc), and WIFSTOPPED(*stat_loc) shall evaluate to a non-zero value.
If the information pointed to by stat_loc was stored by a call to waitpid() that specified the WUNTRACED and WCONTINUED flags, exactly one of the macros WIFEXITED(*stat_loc), WIFSIGNALED(*stat_loc), WIFSTOPPED(*stat_loc), and WIFCONTINUED(*stat_loc) shall evaluate to a non-zero value.
If the information pointed to by stat_loc was stored by a call to waitpid() that did not specify the WUNTRACED or WCONTINUED flags, or by a call to the wait() function, exactly one of the macros WIFEXITED(*stat_loc) and WIFSIGNALED(*stat_loc) shall evaluate to a non-zero value.
If the information pointed to by stat_loc was stored by a call to waitpid() that did not specify the WUNTRACED flag and specified the WCONTINUED flag, exactly one of the macros WIFEXITED(*stat_loc), WIFSIGNALED(*stat_loc), and WIFCONTINUED(*stat_loc) shall evaluate to a non-zero value.
If _POSIX_REALTIME_SIGNALS is defined, and the implementation queues the SIGCHLD signal, then if wait() or waitpid() returns because the status of a child process is available, any pending SIGCHLD signal associated with the process ID of the child process shall be discarded. Any other pending SIGCHLD signals shall remain pending.
Otherwise, if SIGCHLD is blocked, if wait() or waitpid() return because the status of a child process is available, any pending SIGCHLD signal shall be cleared unless the status of another child process is available.
For all other conditions, it is unspecified whether child status will be available when a SIGCHLD signal is delivered.
There may be additional implementation-defined circumstances under which wait() or waitpid() report status. This shall not occur unless the calling process or one of its child processes explicitly makes use of a non-standard extension. In these cases the interpretation of the reported status is implementation-defined.
If a parent process terminates without waiting for all of its child processes to terminate, the remaining child processes shall be assigned a new parent process ID corresponding to an implementation-defined system process. (adopted, basically ๐ฅบ)
๐ฅ RETURN VALUE ๐ฅ
If wait() or waitpid() returns because the status of a child process is available, these functions shall return a value equal to the process ID of the child process for which status is reported. If wait() or waitpid() returns due to the delivery of a signal to the calling process, -1 shall be returned and errno set to [EINTR]. If waitpid() was invoked with WNOHANG set in options, it has at least one child process specified by pid for which status is not available, and status is not available for any process specified by pid, 0 is returned. Otherwise, -1 shall be returned, and errno set to indicate the error.
๐ ERRORS ๐
The wait() function shall fail if:
ECHILDโ the calling process has no existing unwaited-for child processes.EINTRโ the function was interrupted by a signal. The value of the location pointed to bystat_locis undefined.
The waitpid() function shall fail if:
ECHILDโ the process specified bypiddoes not exist or is not a child of the calling process, or the process group specified bypiddoes not exist or does not have any member process that is a child of the calling process.EINTRโ the function was interrupted by a signal. The value of the location pointed to bystat_locis undefined.EINVALโ theoptionsargument is not valid.
The following sections are informative.
โจ EXAMPLES โจ
Okay bestie, this is the part where it gets real โ actual code you can stare at. Two whole scenarios, both iconic, both worth reading twice. ๐ซถ
๐ธ Waiting for a Child Process and then Checking its Status ๐ธ
So this example shows off waitpid(), fork(), and all those little macros you use to decode the status value that waitpid() (and wait()) hands back to you. What's happening: we spin up a child process that does some unspecified work, and meanwhile the parent just... loops, calling waitpid() over and over to keep an eye on the child's status. The loop only bails once it detects that the child has terminated. ๐
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
...
pid_t child_pid, wpid;
int status;
child_pid = fork();
if (child_pid == -1) { /* fork() failed */
perror("fork");
exit(EXIT_FAILURE);
}
if (child_pid == 0) { /* This is the child */
/* Child does some work and then terminates */
...
} else { /* This is the parent */
do {
wpid = waitpid(child_pid, &status, WUNTRACED
#ifdef WCONTINUED /* Not all implementations support this */
| WCONTINUED
#endif
);
if (wpid == -1) {
perror("waitpid");
exit(EXIT_FAILURE);
}
if (WIFEXITED(status)) {
printf("child exited, status=%d\n", WEXITSTATUS(status));
} else if (WIFSIGNALED(status)) {
printf("child killed (signal %d)\n", WTERMSIG(status));
} else if (WIFSTOPPED(status)) {
printf("child stopped (signal %d)\n", WSTOPSIG(status));
#ifdef WIFCONTINUED /* Not all implementations support this */
} else if (WIFCONTINUED(status)) {
printf("child continued\n");
#endif
} else { /* Non-standard case -- may never happen */
printf("Unexpected status (0x%x)\n", status);
}
} while (!WIFEXITED(status) && !WIFSIGNALED(status));
}
๐ฆ Waiting for a Child Process in a Signal Handler for SIGCHLD ๐ฆ
This one is giving advanced. It shows you how to use waitpid() inside a signal handler for SIGCHLD without passing -1 as the pid argument. (If you're wondering why anyone would avoid -1, peep the APPLICATION USAGE section down below โ it spills the tea. โ)
The trick here leans on the standard behavior of waitpid() when SIGCHLD is blocked. But heads up, bestie: on historical non-conforming systems, the status of some child processes might not get reported. ๐ So like, know your system.
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#define CHILDREN 10
static void
handle_sigchld(int signum, siginfo_t *sinfo, void *unused)
{
int sav_errno = errno;
int status;
/*
* Obtain status information for the child which
* caused the SIGCHLD signal and write its exit code
* to stdout.
*/
if (sinfo->si_code != CLD_EXITED)
{
static char msg[] = "wrong si_code\n";
write(2, msg, sizeof msg - 1);
}
else if (waitpid(sinfo->si_pid, &status, 0) == -1)
{
static char msg[] = "waitpid() failed\n";
write(2, msg, sizeof msg - 1);
}
else if (!WIFEXITED(status))
{
static char msg[] = "WIFEXITED was false\n";
write(2, msg, sizeof msg - 1);
}
else
{
int code = WEXITSTATUS(status);
char buf[2];
buf[0] = '0' + code;
buf[1] = '\n';
write(1, buf, 2);
}
errno = sav_errno;
}
int
main(void)
{
int i;
pid_t pid;
struct sigaction sa;
sa.sa_flags = SA_SIGINFO;
sa.sa_sigaction = handle_sigchld;
sigemptyset(&sa.sa_mask);
if (sigaction(SIGCHLD, &sa, NULL) == -1)
{
perror("sigaction");
exit(EXIT_FAILURE);
}
for (i = 0; i < CHILDREN; i++)
{
switch (pid = fork())
{
case -1:
perror("fork");
exit(EXIT_FAILURE);
case 0:
sleep(2);
_exit(i);
}
}
/* Wait for all the SIGCHLD signals, then terminate on SIGALRM */
alarm(3);
for (;;)
pause();
return 0; /* NOTREACHED */
}
๐ APPLICATION USAGE ๐
Okay so real talk. Calls to wait() will collect information about any child process. That means it can interact with other interfaces that are also waiting on their own children โ think stuff like system(). ๐ฌ
For this reason and a whole list of others, it's recommended that portable applications do not use wait(), and instead use waitpid(). Slay, waitpid(), you're the moment.
And for those same exact reasons? Using waitpid() with a pid argument of -1, and using waitid() with the idtype argument set to P_ALL, are also not recommended for portable applications. ๐ซ
Not me telling you twice: if you want your code to travel well,wait()andpid == -1are not the vibe.waitpid()with an actual pid is the move. Periodt. ๐
Now, as specified in Consequences of Process Termination: if the calling process has SA_NOCLDWAIT set, or has SIGCHLD set to SIG_IGN, then a child process terminating will not cause status information to become available to a thread blocked in wait(), waitid(), or waitpid(). ๐ญ
Which means โ and this is the part that lowkey bites people โ a thread blocked in one of the wait functions will just stay blocked, unless some other condition causes that thread to resume execution. What kind of other condition? Well, like an [ECHILD] failure, which happens when there are no remaining children in the set of waited-for children. ๐ฅ
So yeah: no children left to wait on, and your thread finally gets to go about its day. Iconic behavior, honestly. โจ
๐ญ RATIONALE ๐ญ
okay so real talk, bestie โ wait() and waitpid() only hand you status for an immediate child of the calling process. like, a child produced by a single fork() call (maybe followed by an exec or other function calls) from the parent. if that child goes and makes grandbabies with more fork()s? none of those grandkids, and none of their descendants, affect what a wait() from the original parent does. nada. zip. ๐
nothing in this volume of POSIX.1โ2017 stops an implementation from providing extensions that let a process get status from a grandchild or literally any other process โ but a process that doesn't use such extensions must be guaranteed to see status from only its direct children. periodt.
the waitpid() function exists for three reasons, and they're all iconic:
- to support job control
- to permit a non-blocking version of the
wait()function - to permit a library routine, such as
system()orpclose(), to wait for its children without interfering with other terminated children for which the process has not waited
the first two of these facilities are based on the wait3() function provided by 4.3 BSD. the function uses the options argument, which is equivalent to an argument to wait3(). the WUNTRACED flag is used only in conjunction with job control on systems supporting job control. its name comes from 4.3 BSD and refers to the fact that there are two types of stopped processes in that implementation: processes being traced via the ptrace() debugging facility, and (untraced) processes stopped by job control signals. since ptrace() is not part of this volume of POSIX.1โ2017, only the second type is relevant. the name WUNTRACED was retained because its usage is the same, even though the name is not intuitively meaningful in this context. iykyk ๐ซถ
the third reason for waitpid() is to permit independent sections of a process to spawn and wait for children without interfering with each other. for example, the following problem occurs in developing a portable shell, or command interpreter:
stream = popen("/bin/true");
(void) system("sleep 100");
(void) pclose(stream);
on all historical implementations, the final pclose() fails to reap the wait() status of the popen(). ๐ญ the audacity.
the status values are retrieved by macros, rather than given as specific bit encodings like they are in most historical implementations (and thus expected by existing programs). this was necessary to eliminate a limitation on the number of signals an implementation can support that was inherent in the traditional encodings. this volume of POSIX.1โ2017 does require that a status value of zero corresponds to a process calling _exit(0), since that's the most common encoding expected by existing programs. some of the macro names were adopted from 4.3 BSD. ๐
these macros syntactically operate on an arbitrary integer value. the behavior is undefined unless that value is one stored by a successful call to wait() or waitpid() in the location pointed to by the stat_loc argument. an early proposal tried to make this clearer by specifying each argument as *stat_loc rather than stat_val. however, that did not follow the conventions of other specifications in this volume of POSIX.1โ2017 or traditional usage. it also could have implied that the argument to the macro must literally be *stat_loc; in fact, that value can be stored or passed as an argument to other functions before being interpreted by these macros. no cap.
the extension that affects wait() and waitpid() and is common in historical implementations is the ptrace() function. it's called by a child process and causes that child to stop and return a status that appears identical to the status indicated by WIFSTOPPED. the status of ptrace() children is traditionally returned regardless of the WUNTRACED flag (or by the wait() function). most applications don't need to concern themselves with such extensions because they have control over what extensions they or their children use. but applications like command interpreters that invoke arbitrary processes may see this behavior when those arbitrary processes misuse such extensions. ๐
implementations that support core file creation or other implementation-defined actions on termination of some processes traditionally provide a bit in the status returned by wait() to indicate that such actions have occurred. noted. โจ
allowing the wait() family of functions to discard a pending SIGCHLD signal that is associated with a successfully waited-for child process puts them into the sigwait() and sigwaitinfo() category with respect to SIGCHLD. ๐ธ
this definition allows implementations to treat a pending SIGCHLD signal as accepted by the process in wait(), with the same meaning of "accepted" as when that word is applied to the sigwait() family of functions.
allowing the wait() family of functions to behave this way permits an implementation to be able to deal precisely with SIGCHLD signals. ๐ฏ
in particular, an implementation that does accept (discard) the SIGCHLD signal can make the following guarantees regardless of the queuing depth of signals in general (the list of waitable children can hold the SIGCHLD queue):
- if a
SIGCHLDsignal handler is established viasigaction()without theSA_RESETHANDflag,SIGCHLDsignals can be accurately counted; that is, exactly oneSIGCHLDsignal will be delivered to or accepted by the process for every child process that terminates. - a single
wait()issued from aSIGCHLDsignal handler can be guaranteed to return immediately with status information for a child process. - when
SA_SIGINFOis requested, theSIGCHLDsignal handler can be guaranteed to receive a non-null pointer to asiginfo_tstructure that describes a child process for which a wait viawaitpid()orwaitid()will not block or fail. - the
system()function will not cause theSIGCHLDhandler of a process to be called as a result of thefork()/execexecuted withinsystem()becausesystem()will accept theSIGCHLDsignal when it performs awaitpid()for its child process. this is a desirable behavior ofsystem()so that it can be used in a library without causing side-effects to the application linked with the library. ๐
an implementation that does not permit the wait() family of functions to accept (discard) a pending SIGCHLD signal associated with a successfully waited-for child cannot make the guarantees described above, for the following reasons:
๐ซ Guarantee #1
although it might be assumed that reliable queuing of all SIGCHLD signals generated by the system can make this guarantee, the counter-example is the case of a process that blocks SIGCHLD and performs an indefinite loop of fork()/wait() operations. if the implementation supports queued signals, then eventually the system will run out of memory for the queue. the guarantee cannot be made because there must be some limit to the depth of queuing.
๐ซ Guarantees #2 and #3
these cannot be guaranteed unless the wait() family of functions accepts the SIGCHLD signal. otherwise, a fork()/wait() executed while SIGCHLD is blocked (as in the system() function) will result in an invocation of the handler when SIGCHLD is unblocked, after the process has disappeared. ๐
๐ซ Guarantee #4
although possible to make this guarantee, system() would have to set the SIGCHLD handler to SIG_DFL so that the SIGCHLD signal generated by its fork() would be discarded (the SIGCHLD default action is to be ignored), then restore it to its previous setting. this would have the undesirable side-effect of discarding all SIGCHLD signals pending to the process. ๐ฅฒ
๐ฎ FUTURE DIRECTIONS ๐ฎ
None.
like... literally nothing. the future is a blank canvas bestie. โจ
๐ SEE ALSO ๐
- Section 2.13, Status Information,
exec,exit(),fork(),system(),waitid() - The Base Definitions volume of POSIX.1โ2017, Section 4.12, Memory Synchronization,
<signal.h>,<sys_wait.h>
go read those too, they're giving main character energy. ๐
๐ COPYRIGHT ๐
Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1-2017, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 7, 2018 Edition, Copyright (C) 2018 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .
Any typographical or formatting errors that appear in this page are most likely to have been introduced during the conversion of the source files to man page format. To report such errors, see https://www.kernel.org/doc/man-pages/reporting_bugs.html .
and that's the whole page, bestie!! ๐ this was brought to you by IEEE/The Open Group, 2017, and the icon that is WAIT(3POSIX) โ you read the entire thing, slay, go reap some children responsibly ๐๐ฆ
๐ฆ where this page comes from
- debian bookworm: manpages-posix-dev 2017a-2 ยท Other
- debian trixie: manpages-posix-dev 2017a-2 ยท Other
- ubuntu jammy: manpages-posix-dev 2017a-2 ยท Other
- ubuntu noble: manpages-posix-dev 2017a-2 ยท Other
- ubuntu resolute: manpages-posix-dev 2017a-2build1 ยท Other
- ubuntu stonking: manpages-posix-dev 2017a-2.1 ยท Other
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms