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
11

NAME

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

SYNOPSIS

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

DESCRIPTION

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

RETURN VALUE

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

ERRORS

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

EXAMPLES

232   Waiting for a Child Process and then Checking its Status
233       The following example demonstrates the use of  waitpid(),  fork(),  and
234       the  macros  used  to  interpret the status value returned by waitpid()
235       (and wait()).  The code segment creates a child process which does some
236       unspecified  work. Meanwhile the parent loops performing calls to wait‐
237       pid() to monitor the status of the  child.  The  loop  terminates  when
238       child termination is detected.
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           #include <stdlib.h>
299           #include <stdio.h>
300           #include <signal.h>
301           #include <sys/types.h>
302           #include <sys/wait.h>
303           #include <unistd.h>
304
305           #define CHILDREN 10
306
307           static void
308           handle_sigchld(int signum, siginfo_t *sinfo, void *unused)
309           {
310               int sav_errno = errno;
311               int status;
312
313               /*
314                * Obtain status information for the child which
315                * caused the SIGCHLD signal and write its exit code
316                * to stdout.
317               */
318               if (sinfo->si_code != CLD_EXITED)
319               {
320                   static char msg[] = "wrong si_code\n";
321                   write(2, msg, sizeof msg − 1);
322               }
323               else if (waitpid(sinfo->si_pid, &status, 0) == −1)
324               {
325                   static char msg[] = "waitpid() failed\n";
326                   write(2, msg, sizeof msg − 1);
327               }
328               else if (!WIFEXITED(status))
329               {
330                   static char msg[] = "WIFEXITED was false\n";
331                   write(2, msg, sizeof msg − 1);
332               }
333               else
334               {
335                   int code = WEXITSTATUS(status);
336                   char buf[2];
337                   buf[0] = '0' + code;
338                   buf[1] = '\n';
339                   write(1, buf, 2);
340               }
341               errno = sav_errno;
342           }
343
344           int
345           main(void)
346           {
347               int i;
348               pid_t pid;
349               struct sigaction sa;
350
351               sa.sa_flags = SA_SIGINFO;
352               sa.sa_sigaction = handle_sigchld;
353               sigemptyset(&sa.sa_mask);
354               if (sigaction(SIGCHLD, &sa, NULL) == −1)
355               {
356                   perror("sigaction");
357                   exit(EXIT_FAILURE);
358               }
359
360               for (i = 0; i < CHILDREN; i++)
361               {
362                   switch (pid = fork())
363                   {
364                   case −1:
365                       perror("fork");
366                       exit(EXIT_FAILURE);
367                   case 0:
368                       sleep(2);
369                       _exit(i);
370                   }
371               }
372
373               /* Wait for all the SIGCHLD signals, then terminate on SIGALRM */
374               alarm(3);
375               for (;;)
376                   pause();
377
378               return 0; /* NOTREACHED */
379           }
380

APPLICATION USAGE

382       Calls to wait() will collect information about any child process.  This
383       may  result  in  interactions with other interfaces that may be waiting
384       for their own children (such as by use  of  system()).   For  this  and
385       other  reasons  it  is  recommended  that portable applications not use
386       wait(), but instead use waitpid().  For these same reasons, the use  of
387       waitpid()  with  a pid argument of −1, and the use of waitid() with the
388       idtype argument set to P_ALL, are also  not  recommended  for  portable
389       applications.
390

RATIONALE

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

FUTURE DIRECTIONS

543       None.
544

SEE ALSO

546       exec, exit(), fork(), system(), waitid()
547
548       The Base Definitions volume of POSIX.1‐2008, Section 4.11, Memory  Syn‐
549       chronization, <signal.h>, <sys_wait.h>
550
552       Portions  of  this text are reprinted and reproduced in electronic form
553       from IEEE Std 1003.1, 2013 Edition, Standard for Information Technology
554       --  Portable  Operating  System  Interface (POSIX), The Open Group Base
555       Specifications Issue 7, Copyright (C) 2013 by the Institute of Electri‐
556       cal  and  Electronics  Engineers,  Inc  and  The  Open Group.  (This is
557       POSIX.1-2008 with the 2013 Technical Corrigendum  1  applied.)  In  the
558       event of any discrepancy between this version and the original IEEE and
559       The Open Group Standard, the original IEEE and The Open Group  Standard
560       is  the  referee document. The original Standard can be obtained online
561       at http://www.unix.org/online.html .
562
563       Any typographical or formatting errors that appear  in  this  page  are
564       most likely to have been introduced during the conversion of the source
565       files to man page format. To report such errors,  see  https://www.ker
566       nel.org/doc/man-pages/reporting_bugs.html .
567
568
569
570IEEE/The Open Group                  2013                             WAIT(3P)
Impressum