#include <sys/wait.h> pid_t wait(int *stat_loc); pid_t waitpid(pid_t pid, int *stat_loc, int options);
The wait() function 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. If termination status information is available for two or more child processes, the order in which their status is reported is unspecified.
As described in Section 2.13, Status Information, the wait() and waitpid() functions consume the status information they obtain.
The behavior when multiple threads are blocked in wait(), waitid(), or waitpid() is described in Section 2.13, Status Information.
The waitpid() function 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. The waitpid() function shall only return the status of a child process from this set:
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:
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:
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.
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.
The waitpid() function shall fail if:
The following sections are informative.
The following example demonstrates the use of waitpid(), fork(), and the macros used to interpret the status value returned by waitpid() (and wait()). The code segment creates a child process which does some unspecified work. Meanwhile the parent loops performing calls to waitpid() to monitor the status of the child. The loop terminates when child termination is detected.
#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)); }
The following example demonstrates how to use waitpid() in a signal handler for SIGCHLD without passing -1 as the pid argument. (See the APPLICATION USAGE section below for the reasons why passing a pid of -1 is not recommended.) The method used here relies on the standard behavior of waitpid() when SIGCHLD is blocked. On historical non-conforming systems, the status of some child processes might not be reported.
#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 */ }
As specified in Consequences of Process Termination, if the calling process has SA_NOCLDWAIT set or has SIGCHLD set to SIG_IGN, then the termination of a child process will not cause status information to become available to a thread blocked in wait(), waitid(), or waitpid(). Thus, a thread blocked in one of the wait functions will remain blocked unless some other condition causes the thread to resume execution (such as an [ECHILD] failure due to no remaining children in the set of waited-for children).
The waitpid() function is provided for three reasons:
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.
The third reason for the waitpid() function 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 status values are retrieved by macros, rather than given as specific bit encodings as 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), as this is 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 attempted 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.
The extension that affects wait() and waitpid() and is common in historical implementations is the ptrace() function. It is 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 do not need to concern themselves with such extensions because they have control over what extensions they or their children use. However, applications, such as 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.
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):
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:
The Base Definitions volume of POSIX.1-2017, Section 4.12, Memory Synchronization, <signal.h>, <sys_wait.h>
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 .