1WAIT(3P)                   POSIX Programmer's Manual                  WAIT(3P)
2
3
4

PROLOG

6       This  manual  page is part of the POSIX Programmer's Manual.  The Linux
7       implementation of this interface may differ (consult the  corresponding
8       Linux  manual page for details of Linux behavior), or the interface may
9       not be implemented on Linux.
10

NAME

12       wait, waitpid — wait for a child process to stop or terminate
13

SYNOPSIS

15       #include <sys/wait.h>
16
17       pid_t wait(int *stat_loc);
18       pid_t waitpid(pid_t pid, int *stat_loc, int options);
19

DESCRIPTION

21       The wait() and waitpid() functions shall obtain status information (see
22       Section  2.13,  Status  Information)  pertaining to one of the caller's
23       child processes. The wait() function  obtains  status  information  for
24       process  termination  from  any  child  process. The waitpid() function
25       obtains status information  for  process  termination,  and  optionally
26       process stop and/or continue, from a specified subset of the child pro‐
27       cesses.
28
29       The wait() function shall cause the calling thread  to  become  blocked
30       until status information generated by child process termination is made
31       available to the thread, or until delivery of a signal whose action  is
32       either  to  execute  a  signal-catching  function  or  to terminate the
33       process, or an error  occurs.  If  termination  status  information  is
34       available  prior  to  the call to wait(), return shall be immediate. If
35       termination status information is available for two or more child  pro‐
36       cesses, the order in which their status is reported is unspecified.
37
38       As  described in Section 2.13, Status Information, the wait() and wait‐
39       pid() functions consume the status information they obtain.
40
41       The behavior when multiple threads are blocked in wait(), waitid(),  or
42       waitpid() is described in Section 2.13, Status Information.
43
44       The  waitpid()  function shall be equivalent to wait() if the pid argu‐
45       ment is (pid_t)-1 and the options argument is 0. Otherwise, its  behav‐
46       ior shall be modified by the values of the pid and options arguments.
47
48       The pid argument specifies a set of child processes for which status is
49       requested. The waitpid() function shall only return  the  status  of  a
50       child process from this set:
51
52        *  If  pid  is  equal  to (pid_t)-1, status is requested for any child
53           process. In this respect, waitpid() is then equivalent to wait().
54
55        *  If pid is greater than 0, it specifies the process ID of  a  single
56           child process for which status is requested.
57
58        *  If  pid  is  0,  status  is  requested  for any child process whose
59           process group ID is equal to that of the calling process.
60
61        *  If pid is less than (pid_t)-1, status is requested  for  any  child
62           process  whose  process  group ID is equal to the absolute value of
63           pid.
64
65       The options argument is constructed from the  bitwise-inclusive  OR  of
66       zero  or  more  of  the  following  flags,  defined in the <sys/wait.h>
67       header:
68
69       WCONTINUED  The waitpid() function shall report the status of any  con‐
70                   tinued  child process specified by pid whose status has not
71                   been reported since it continued from a job control stop.
72
73       WNOHANG     The waitpid() function shall not suspend execution  of  the
74                   calling  thread  if status is not immediately available for
75                   one of the child processes specified by pid.
76
77       WUNTRACED   The status of any child processes specified by pid that are
78                   stopped,  and  whose status has not yet been reported since
79                   they stopped, shall also  be  reported  to  the  requesting
80                   process.
81
82       If  wait() or waitpid() return because the status of a child process is
83       available, these functions shall return a value equal to the process ID
84       of  the  child  process.  In  this  case,  if the value of the argument
85       stat_loc is not a null pointer, information  shall  be  stored  in  the
86       location  pointed  to  by  stat_loc.   The value stored at the location
87       pointed to by stat_loc shall be 0 if and only if the status returned is
88       from a terminated child process that terminated by one of the following
89       means:
90
91        1. The process returned 0 from main().
92
93        2. The process called _exit() or exit() with a status argument of 0.
94
95        3. The process was terminated because the last thread in  the  process
96           terminated.
97
98       Regardless  of its value, this information may be interpreted using the
99       following macros, which are defined in  <sys/wait.h>  and  evaluate  to
100       integral  expressions;  the  stat_val  argument  is  the  integer value
101       pointed to by stat_loc.
102
103       WIFEXITED(stat_val)
104             Evaluates to a non-zero value if status was returned for a  child
105             process that terminated normally.
106
107       WEXITSTATUS(stat_val)
108             If the value of WIFEXITED(stat_val) is non-zero, this macro eval‐
109             uates to the low-order 8 bits of the  status  argument  that  the
110             child process passed to _exit() or exit(), or the value the child
111             process returned from main().
112
113       WIFSIGNALED(stat_val)
114             Evaluates to a non-zero value if status was returned for a  child
115             process  that  terminated due to the receipt of a signal that was
116             not caught (see <signal.h>).
117
118       WTERMSIG(stat_val)
119             If the value of WIFSIGNALED(stat_val)  is  non-zero,  this  macro
120             evaluates to the number of the signal that caused the termination
121             of the child process.
122
123       WIFSTOPPED(stat_val)
124             Evaluates to a non-zero value if status was returned for a  child
125             process that is currently stopped.
126
127       WSTOPSIG(stat_val)
128             If  the  value  of  WIFSTOPPED(stat_val)  is non-zero, this macro
129             evaluates to the number of  the  signal  that  caused  the  child
130             process to stop.
131
132       WIFCONTINUED(stat_val)
133             Evaluates  to a non-zero value if status was returned for a child
134             process that has continued from a job control stop.
135
136       It is unspecified whether the status value returned by calls to  wait()
137       or  waitpid()  for processes created by posix_spawn() or posix_spawnp()
138       can indicate a WIFSTOPPED(stat_val) before subsequent calls  to  wait()
139       or  waitpid()  indicate  WIFEXITED(stat_val)  as the result of an error
140       detected before the new process image starts executing.
141
142       It is unspecified whether the status value returned by calls to  wait()
143       or  waitpid()  for processes created by posix_spawn() or posix_spawnp()
144       can indicate a WIFSIGNALED(stat_val) if a signal is sent  to  the  par‐
145       ent's process group after posix_spawn() or posix_spawnp() is called.
146
147       If the information pointed to by stat_loc was stored by a call to wait‐
148       pid() that specified the WUNTRACED flag and did not specify  the  WCON‐
149       TINUED  flag,  exactly  one of the macros WIFEXITED(*stat_loc), WIFSIG‐
150       NALED(*stat_loc), and WIFSTOPPED(*stat_loc) shall evaluate  to  a  non-
151       zero value.
152
153       If the information pointed to by stat_loc was stored by a call to wait‐
154       pid() that specified the WUNTRACED and WCONTINUED flags, exactly one of
155       the    macros    WIFEXITED(*stat_loc),   WIFSIGNALED(*stat_loc),   WIF‐
156       STOPPED(*stat_loc), and WIFCONTINUED(*stat_loc)  shall  evaluate  to  a
157       non-zero value.
158
159       If the information pointed to by stat_loc was stored by a call to wait‐
160       pid() that did not specify the WUNTRACED or WCONTINUED flags, or  by  a
161       call  to  the  wait()  function,  exactly  one  of  the  macros  WIFEX‐
162       ITED(*stat_loc) and WIFSIGNALED(*stat_loc) shall evaluate to a non-zero
163       value.
164
165       If the information pointed to by stat_loc was stored by a call to wait‐
166       pid() that did not specify the WUNTRACED flag and specified  the  WCON‐
167       TINUED  flag,  exactly  one of the macros WIFEXITED(*stat_loc), WIFSIG‐
168       NALED(*stat_loc), and WIFCONTINUED(*stat_loc) shall evaluate to a  non-
169       zero value.
170
171       If  _POSIX_REALTIME_SIGNALS  is  defined, and the implementation queues
172       the SIGCHLD signal, then if wait() or  waitpid()  returns  because  the
173       status  of  a  child  process  is available, any pending SIGCHLD signal
174       associated with the process ID of the child process shall be discarded.
175       Any other pending SIGCHLD signals shall remain pending.
176
177       Otherwise, if SIGCHLD is blocked, if wait() or waitpid() return because
178       the status of a child process is available, any pending SIGCHLD  signal
179       shall  be  cleared unless the status of another child process is avail‐
180       able.
181
182       For all other conditions, it is unspecified whether child  status  will
183       be available when a SIGCHLD signal is delivered.
184
185       There  may  be  additional  implementation-defined  circumstances under
186       which wait() or waitpid() report status.  This shall not  occur  unless
187       the  calling process or one of its child processes explicitly makes use
188       of a non-standard extension. In these cases the interpretation  of  the
189       reported status is implementation-defined.
190
191       If  a  parent  process  terminates without waiting for all of its child
192       processes to terminate, the remaining child processes shall be assigned
193       a new parent process ID corresponding to an implementation-defined sys‐
194       tem process.
195

RETURN VALUE

197       If wait() or waitpid() returns because the status of a child process is
198       available, these functions shall return a value equal to the process ID
199       of the child process for which status is reported. If wait()  or  wait‐
200       pid()  returns  due to the delivery of a signal to the calling process,
201       -1 shall be returned and  errno  set  to  [EINTR].   If  waitpid()  was
202       invoked  with WNOHANG set in options, it has at least one child process
203       specified by pid for which status is not available, and status  is  not
204       available  for  any process specified by pid, 0 is returned. Otherwise,
205       -1 shall be returned, and errno set to indicate the error.
206

ERRORS

208       The wait() function shall fail if:
209
210       ECHILD The calling process has  no  existing  unwaited-for  child  pro‐
211              cesses.
212
213       EINTR  The function was interrupted by a signal. The value of the loca‐
214              tion pointed to by stat_loc is undefined.
215
216       The waitpid() function shall fail if:
217
218       ECHILD The process specified by pid does not exist or is not a child of
219              the  calling process, or the process group specified by pid does
220              not exist or does not have any member process that is a child of
221              the calling process.
222
223       EINTR  The function was interrupted by a signal. The value of the loca‐
224              tion pointed to by stat_loc is undefined.
225
226       EINVAL The options argument is not valid.
227
228       The following sections are informative.
229

EXAMPLES

231   Waiting for a Child Process and then Checking its Status
232       The following example demonstrates the use of  waitpid(),  fork(),  and
233       the  macros  used  to  interpret the status value returned by waitpid()
234       (and wait()).  The code segment creates a child process which does some
235       unspecified  work. Meanwhile the parent loops performing calls to wait‐
236       pid() to monitor the status of the  child.  The  loop  terminates  when
237       child termination is detected.
238
239
240           #include <stdio.h>
241           #include <stdlib.h>
242           #include <unistd.h>
243           #include <sys/wait.h>
244           ...
245
246           pid_t child_pid, wpid;
247           int status;
248
249           child_pid = fork();
250           if (child_pid == -1) {      /* fork() failed */
251               perror("fork");
252               exit(EXIT_FAILURE);
253           }
254
255           if (child_pid == 0) {       /* This is the child */
256               /* Child does some work and then terminates */
257               ...
258
259           } else {                    /* This is the parent */
260               do {
261                   wpid = waitpid(child_pid, &status, WUNTRACED
262           #ifdef WCONTINUED       /* Not all implementations support this */
263                   | WCONTINUED
264           #endif
265                   );
266                   if (wpid == -1) {
267                       perror("waitpid");
268                       exit(EXIT_FAILURE);
269                   }
270
271                   if (WIFEXITED(status)) {
272                       printf("child exited, status=%d\n", WEXITSTATUS(status));
273
274                   } else if (WIFSIGNALED(status)) {
275                       printf("child killed (signal %d)\n", WTERMSIG(status));
276
277                   } else if (WIFSTOPPED(status)) {
278                       printf("child stopped (signal %d)\n", WSTOPSIG(status));
279
280           #ifdef WIFCONTINUED     /* Not all implementations support this */
281                   } else if (WIFCONTINUED(status)) {
282                       printf("child continued\n");
283           #endif
284                   } else {    /* Non-standard case -- may never happen */
285                       printf("Unexpected status (0x%x)\n", status);
286                   }
287               } while (!WIFEXITED(status) && !WIFSIGNALED(status));
288           }
289
290   Waiting for a Child Process in a Signal Handler for SIGCHLD
291       The  following  example  demonstrates  how to use waitpid() in a signal
292       handler for SIGCHLD without passing -1 as the pid  argument.  (See  the
293       APPLICATION USAGE section below for the reasons why passing a pid of -1
294       is not recommended.) The method used here relies on the standard behav‐
295       ior  of waitpid() when SIGCHLD is blocked. On historical non-conforming
296       systems, the status of some child processes might not be reported.
297
298
299           #include <stdlib.h>
300           #include <stdio.h>
301           #include <signal.h>
302           #include <sys/types.h>
303           #include <sys/wait.h>
304           #include <unistd.h>
305
306           #define CHILDREN 10
307
308           static void
309           handle_sigchld(int signum, siginfo_t *sinfo, void *unused)
310           {
311               int sav_errno = errno;
312               int status;
313
314               /*
315                * Obtain status information for the child which
316                * caused the SIGCHLD signal and write its exit code
317                * to stdout.
318               */
319               if (sinfo->si_code != CLD_EXITED)
320               {
321                   static char msg[] = "wrong si_code\n";
322                   write(2, msg, sizeof msg - 1);
323               }
324               else if (waitpid(sinfo->si_pid, &status, 0) == -1)
325               {
326                   static char msg[] = "waitpid() failed\n";
327                   write(2, msg, sizeof msg - 1);
328               }
329               else if (!WIFEXITED(status))
330               {
331                   static char msg[] = "WIFEXITED was false\n";
332                   write(2, msg, sizeof msg - 1);
333               }
334               else
335               {
336                   int code = WEXITSTATUS(status);
337                   char buf[2];
338                   buf[0] = '0' + code;
339                   buf[1] = '\n';
340                   write(1, buf, 2);
341               }
342               errno = sav_errno;
343           }
344
345           int
346           main(void)
347           {
348               int i;
349               pid_t pid;
350               struct sigaction sa;
351
352               sa.sa_flags = SA_SIGINFO;
353               sa.sa_sigaction = handle_sigchld;
354               sigemptyset(&sa.sa_mask);
355               if (sigaction(SIGCHLD, &sa, NULL) == -1)
356               {
357                   perror("sigaction");
358                   exit(EXIT_FAILURE);
359               }
360
361               for (i = 0; i < CHILDREN; i++)
362               {
363                   switch (pid = fork())
364                   {
365                   case -1:
366                       perror("fork");
367                       exit(EXIT_FAILURE);
368                   case 0:
369                       sleep(2);
370                       _exit(i);
371                   }
372               }
373
374               /* Wait for all the SIGCHLD signals, then terminate on SIGALRM */
375               alarm(3);
376               for (;;)
377                   pause();
378
379               return 0; /* NOTREACHED */
380           }
381

APPLICATION USAGE

383       Calls to wait() will collect information about any child process.  This
384       may  result  in  interactions with other interfaces that may be waiting
385       for their own children (such as by use  of  system()).   For  this  and
386       other  reasons  it  is  recommended  that portable applications not use
387       wait(), but instead use waitpid().  For these same reasons, the use  of
388       waitpid()  with  a pid argument of -1, and the use of waitid() with the
389       idtype argument set to P_ALL, are also  not  recommended  for  portable
390       applications.
391
392       As  specified  in  Consequences  of Process Termination, if the calling
393       process has SA_NOCLDWAIT set or has SIGCHLD set to  SIG_IGN,  then  the
394       termination  of  a  child  process will not cause status information to
395       become available to a thread blocked in wait(), waitid(), or waitpid().
396       Thus, a thread blocked in one of the wait functions will remain blocked
397       unless some other condition causes the thread to resume execution (such
398       as  an  [ECHILD]  failure  due  to  no remaining children in the set of
399       waited-for children).
400

RATIONALE

402       A call to the wait() or waitpid() function only returns  status  on  an
403       immediate  child  process of the calling process; that is, a child that
404       was produced by a single fork() call (perhaps followed by  an  exec  or
405       other  function  calls) from the parent. If a child produces grandchil‐
406       dren by further use of fork(), none of those grandchildren nor  any  of
407       their  descendants  affect  the  behavior of a wait() from the original
408       parent process. Nothing in this  volume  of  POSIX.1‐2017  prevents  an
409       implementation  from  providing extensions that permit a process to get
410       status from a grandchild or any other process, but a process that  does
411       not  use such extensions must be guaranteed to see status from only its
412       direct children.
413
414       The waitpid() function is provided for three reasons:
415
416        1. To support job control
417
418        2. To permit a non-blocking version of the wait() function
419
420        3. To permit a library routine, such as system() or pclose(), to  wait
421           for its children without interfering with other terminated children
422           for which the process has not waited
423
424       The first two of these facilities are based  on  the  wait3()  function
425       provided  by  4.3 BSD. The function uses the options argument, which is
426       equivalent to an argument to wait3().  The WUNTRACED flag is used  only
427       in  conjunction with job control on systems supporting job control. Its
428       name comes from 4.3 BSD and refers to the fact that there are two types
429       of stopped processes in that implementation: processes being traced via
430       the ptrace() debugging facility and (untraced) processes stopped by job
431       control  signals.  Since  ptrace()  is  not  part  of  this  volume  of
432       POSIX.1‐2017, only the second type is relevant. The name WUNTRACED  was
433       retained  because  its  usage  is the same, even though the name is not
434       intuitively meaningful in this context.
435
436       The third reason for the waitpid() function is  to  permit  independent
437       sections  of a process to spawn and wait for children without interfer‐
438       ing with each other. For  example,  the  following  problem  occurs  in
439       developing a portable shell, or command interpreter:
440
441
442           stream = popen("/bin/true");
443           (void) system("sleep 100");
444           (void) pclose(stream);
445
446       On all historical implementations, the final pclose() fails to reap the
447       wait() status of the popen().
448
449       The status values are retrieved by macros, rather than  given  as  spe‐
450       cific bit encodings as they are in most historical implementations (and
451       thus expected by existing programs). This was necessary to eliminate  a
452       limitation  on the number of signals an implementation can support that
453       was inherent in the traditional encodings. This volume of  POSIX.1‐2017
454       does require that a status value of zero corresponds to a process call‐
455       ing _exit(0), as this is the most common encoding expected by  existing
456       programs.  Some of the macro names were adopted from 4.3 BSD.
457
458       These  macros  syntactically operate on an arbitrary integer value. The
459       behavior is undefined unless that value is one stored by  a  successful
460       call  to wait() or waitpid() in the location pointed to by the stat_loc
461       argument. An early proposal attempted to make this clearer by  specify‐
462       ing each argument as *stat_loc rather than stat_val.  However, that did
463       not follow the conventions of other specifications in  this  volume  of
464       POSIX.1‐2017  or traditional usage. It also could have implied that the
465       argument to the macro must literally be *stat_loc; in fact, that  value
466       can  be stored or passed as an argument to other functions before being
467       interpreted by these macros.
468
469       The extension that affects wait() and waitpid() and is common  in  his‐
470       torical  implementations  is  the  ptrace() function. It is called by a
471       child process and causes that child to stop and return  a  status  that
472       appears identical to the status indicated by WIFSTOPPED.  The status of
473       ptrace() children is traditionally returned regardless of the WUNTRACED
474       flag (or by the wait() function). Most applications do not need to con‐
475       cern themselves with such extensions because  they  have  control  over
476       what extensions they or their children use. However, applications, such
477       as command interpreters, that invoke arbitrary processes may  see  this
478       behavior when those arbitrary processes misuse such extensions.
479
480       Implementations  that  support  core file creation or other implementa‐
481       tion-defined actions on termination  of  some  processes  traditionally
482       provide  a  bit  in the status returned by wait() to indicate that such
483       actions have occurred.
484
485       Allowing the wait() family of functions to discard  a  pending  SIGCHLD
486       signal  that is associated with a successfully waited-for child process
487       puts them into the sigwait() and sigwaitinfo() category with respect to
488       SIGCHLD.
489
490       This  definition allows implementations to treat a pending SIGCHLD sig‐
491       nal as accepted by the process in wait(),  with  the  same  meaning  of
492       ``accepted''  as  when  that word is applied to the sigwait() family of
493       functions.
494
495       Allowing the wait() family of functions to behave this way  permits  an
496       implementation to be able to deal precisely with SIGCHLD signals.
497
498       In particular, an implementation that does accept (discard) the SIGCHLD
499       signal can make the following  guarantees  regardless  of  the  queuing
500       depth of signals in general (the list of waitable children can hold the
501       SIGCHLD queue):
502
503        1. If a SIGCHLD signal handler is established via sigaction()  without
504           the  SA_RESETHAND  flag, SIGCHLD signals can be accurately counted;
505           that is, exactly  one  SIGCHLD  signal  will  be  delivered  to  or
506           accepted by the process for every child process that terminates.
507
508        2. A single wait() issued from a SIGCHLD signal handler can be guaran‐
509           teed to return immediately with  status  information  for  a  child
510           process.
511
512        3. When  SA_SIGINFO  is  requested,  the SIGCHLD signal handler can be
513           guaranteed to receive a non-null pointer to a  siginfo_t  structure
514           that  describes  a  child process for which a wait via waitpid() or
515           waitid() will not block or fail.
516
517        4. The system() function will not  cause  the  SIGCHLD  handler  of  a
518           process to be called as a result of the fork()/exec executed within
519           system() because system() will accept the SIGCHLD  signal  when  it
520           performs  a  waitpid()  for  its child process. This is a desirable
521           behavior of system() so that it can be used in  a  library  without
522           causing side-effects to the application linked with the library.
523
524       An  implementation  that does not permit the wait() family of functions
525       to accept (discard) a pending SIGCHLD signal associated with a success‐
526       fully  waited-for child, cannot make the guarantees described above for
527       the following reasons:
528
529       Guarantee #1
530             Although it might be assumed that reliable queuing of all SIGCHLD
531             signals  generated  by  the  system  can make this guarantee, the
532             counter-example is the case of a process that blocks SIGCHLD  and
533             performs  an  indefinite loop of fork()/wait() operations. If the
534             implementation supports queued signals, then eventually the  sys‐
535             tem will run out of memory for the queue. The guarantee cannot be
536             made because there must be some limit to the depth of queuing.
537
538       Guarantees #2 and #3
539             These cannot be guaranteed unless the wait() family of  functions
540             accepts  the  SIGCHLD signal. Otherwise, a fork()/wait() executed
541             while SIGCHLD is blocked  (as  in  the  system()  function)  will
542             result in an invocation of the handler when SIGCHLD is unblocked,
543             after the process has disappeared.
544
545       Guarantee #4
546             Although possible to make this guarantee, system() would have  to
547             set  the  SIGCHLD  handler  to SIG_DFL so that the SIGCHLD signal
548             generated by its fork() would be discarded (the  SIGCHLD  default
549             action  is  to  be ignored), then restore it to its previous set‐
550             ting. This would have the undesirable side-effect  of  discarding
551             all SIGCHLD signals pending to the process.
552

FUTURE DIRECTIONS

554       None.
555

SEE ALSO

557       Section  2.13,  Status  Information,  exec,  exit(),  fork(), system(),
558       waitid()
559
560       The Base Definitions volume of POSIX.1‐2017, Section 4.12, Memory  Syn‐
561       chronization, <signal.h>, <sys_wait.h>
562
564       Portions  of  this text are reprinted and reproduced in electronic form
565       from IEEE Std 1003.1-2017, Standard for Information Technology --  Por‐
566       table  Operating System Interface (POSIX), The Open Group Base Specifi‐
567       cations Issue 7, 2018 Edition, Copyright (C) 2018 by the  Institute  of
568       Electrical  and  Electronics Engineers, Inc and The Open Group.  In the
569       event of any discrepancy between this version and the original IEEE and
570       The  Open Group Standard, the original IEEE and The Open Group Standard
571       is the referee document. The original Standard can be  obtained  online
572       at http://www.opengroup.org/unix/online.html .
573
574       Any  typographical  or  formatting  errors that appear in this page are
575       most likely to have been introduced during the conversion of the source
576       files  to  man page format. To report such errors, see https://www.ker
577       nel.org/doc/man-pages/reporting_bugs.html .
578
579
580
581IEEE/The Open Group                  2017                             WAIT(3P)
Impressum