NEWS: Add advisories.
[glibc.git] / manual / process.texi
blob8254e5ee864e2515190437d48d21c440aca91bfa
1 @node Processes, Inter-Process Communication, Program Basics, Top
2 @c %MENU% How to create processes and run other programs
3 @chapter Processes
5 @cindex process
6 @dfn{Processes} are the primitive units for allocation of system
7 resources.  Each process has its own address space and (usually) one
8 thread of control.  A process executes a program; you can have multiple
9 processes executing the same program, but each process has its own copy
10 of the program within its own address space and executes it
11 independently of the other copies.
13 @cindex child process
14 @cindex parent process
15 Processes are organized hierarchically.  Each process has a @dfn{parent
16 process} which explicitly arranged to create it.  The processes created
17 by a given parent are called its @dfn{child processes}.  A child
18 inherits many of its attributes from the parent process.
20 This chapter describes how a program can create, terminate, and control
21 child processes.  Actually, there are three distinct operations
22 involved: creating a new child process, causing the new process to
23 execute a program, and coordinating the completion of the child process
24 with the original program.
26 The @code{system} function provides a simple, portable mechanism for
27 running another program; it does all three steps automatically.  If you
28 need more control over the details of how this is done, you can use the
29 primitive functions to do each step individually instead.
31 @menu
32 * Running a Command::           The easy way to run another program.
33 * Process Creation Concepts::   An overview of the hard way to do it.
34 * Process Identification::      How to get the process ID of a process.
35 * Creating a Process::          How to fork a child process.
36 * Querying a Process::          How to query a child process.
37 * Executing a File::            How to make a process execute another program.
38 * Process Completion::          How to tell when a child process has completed.
39 * Process Completion Status::   How to interpret the status value
40                                  returned from a child process.
41 * BSD Wait Functions::          More functions, for backward compatibility.
42 * Process Creation Example::    A complete example program.
43 @end menu
46 @node Running a Command
47 @section Running a Command
48 @cindex running a command
50 The easy way to run another program is to use the @code{system}
51 function.  This function does all the work of running a subprogram, but
52 it doesn't give you much control over the details: you have to wait
53 until the subprogram terminates before you can do anything else.
55 @deftypefun int system (const char *@var{command})
56 @standards{ISO, stdlib.h}
57 @pindex sh
58 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuplugin{} @ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{}}}
59 @c system @ascuplugin @ascuheap @asulock @aculock @acsmem
60 @c  do_system @ascuplugin @ascuheap @asulock @aculock @acsmem
61 @c   sigemptyset dup ok
62 @c   libc_lock_lock @asulock @aculock
63 @c   ADD_REF ok
64 @c   sigaction dup ok
65 @c   SUB_REF ok
66 @c   libc_lock_unlock @aculock
67 @c   sigaddset dup ok
68 @c   sigprocmask dup ok
69 @c   CLEANUP_HANDLER @ascuplugin @ascuheap @acsmem
70 @c    libc_cleanup_region_start @ascuplugin @ascuheap @acsmem
71 @c     pthread_cleanup_push_defer @ascuplugin @ascuheap @acsmem
72 @c      cancel_enabled_and_canceled @ascuplugin @ascuheap @acsmem
73 @c       do_cancel @ascuplugin @ascuheap @acsmem
74 @c    cancel_handler ok
75 @c     kill syscall ok
76 @c     waitpid dup ok
77 @c     libc_lock_lock ok
78 @c     sigaction dup ok
79 @c     libc_lock_unlock ok
80 @c   FORK ok
81 @c    clone syscall ok
82 @c   waitpid dup ok
83 @c   CLEANUP_RESET ok
84 @c    libc_cleanup_region_end ok
85 @c     pthread_cleanup_pop_restore ok
86 @c  SINGLE_THREAD_P ok
87 @c  LIBC_CANCEL_ASYNC @ascuplugin @ascuheap @acsmem
88 @c   libc_enable_asynccancel @ascuplugin @ascuheap @acsmem
89 @c    do_cancel dup @ascuplugin @ascuheap @acsmem
90 @c  LIBC_CANCEL_RESET ok
91 @c   libc_disable_asynccancel ok
92 @c    lll_futex_wait dup ok
93 This function executes @var{command} as a shell command.  In @theglibc{},
94 it always uses the default shell @code{sh} to run the command.
95 In particular, it searches the directories in @code{PATH} to find
96 programs to execute.  The return value is @code{-1} if it wasn't
97 possible to create the shell process, and otherwise is the status of the
98 shell process.  @xref{Process Completion}, for details on how this
99 status code can be interpreted.
101 If the @var{command} argument is a null pointer, a return value of zero
102 indicates that no command processor is available.
104 This function is a cancellation point in multi-threaded programs.  This
105 is a problem if the thread allocates some resources (like memory, file
106 descriptors, semaphores or whatever) at the time @code{system} is
107 called.  If the thread gets canceled these resources stay allocated
108 until the program ends.  To avoid this calls to @code{system} should be
109 protected using cancellation handlers.
110 @c ref pthread_cleanup_push / pthread_cleanup_pop
112 @pindex stdlib.h
113 The @code{system} function is declared in the header file
114 @file{stdlib.h}.
115 @end deftypefun
117 @strong{Portability Note:} Some C implementations may not have any
118 notion of a command processor that can execute other programs.  You can
119 determine whether a command processor exists by executing
120 @w{@code{system (NULL)}}; if the return value is nonzero, a command
121 processor is available.
123 The @code{popen} and @code{pclose} functions (@pxref{Pipe to a
124 Subprocess}) are closely related to the @code{system} function.  They
125 allow the parent process to communicate with the standard input and
126 output channels of the command being executed.
128 @node Process Creation Concepts
129 @section Process Creation Concepts
131 This section gives an overview of processes and of the steps involved in
132 creating a process and making it run another program.
134 @cindex creating a process
135 @cindex forking a process
136 @cindex child process
137 @cindex parent process
138 @cindex subprocess
139 A new processes is created when one of the functions
140 @code{posix_spawn}, @code{fork}, @code{_Fork}, @code{vfork}, or
141 @code{pidfd_spawn} is called.  (The @code{system} and @code{popen} also
142 create new processes internally.)  Due to the name of the @code{fork}
143 function, the act of creating a new process is sometimes called
144 @dfn{forking} a process.  Each new process (the @dfn{child process} or
145 @dfn{subprocess}) is allocated a process ID, distinct from the process
146 ID of the parent process.  @xref{Process Identification}.
148 After forking a child process, both the parent and child processes
149 continue to execute normally.  If you want your program to wait for a
150 child process to finish executing before continuing, you must do this
151 explicitly after the fork operation, by calling @code{wait} or
152 @code{waitpid} (@pxref{Process Completion}).  These functions give you
153 limited information about why the child terminated---for example, its
154 exit status code.
156 A newly forked child process continues to execute the same program as
157 its parent process, at the point where the @code{fork} or @code{_Fork}
158 call returns.  You can use the return value from @code{fork} or
159 @code{_Fork} to tell whether the program is running in the parent process
160 or the child.
162 @cindex process image
163 Having several processes run the same program is only occasionally
164 useful.  But the child can execute another program using one of the
165 @code{exec} functions; see @ref{Executing a File}.  The program that the
166 process is executing is called its @dfn{process image}.  Starting
167 execution of a new program causes the process to forget all about its
168 previous process image; when the new program exits, the process exits
169 too, instead of returning to the previous process image.
171 @node Process Identification
172 @section Process Identification
174 @cindex process ID
175 Each process is named by a @dfn{process ID} number, a value of type
176 @code{pid_t}.  A process ID is allocated to each process when it is
177 created.  Process IDs are reused over time.  The lifetime of a process
178 ends when the parent process of the corresponding process waits on the
179 process ID after the process has terminated.  @xref{Process
180 Completion}.  (The parent process can arrange for such waiting to
181 happen implicitly.)  A process ID uniquely identifies a process only
182 during the lifetime of the process.  As a rule of thumb, this means
183 that the process must still be running.
185 Process IDs can also denote process groups and sessions.
186 @xref{Job Control}.
188 @cindex thread ID
189 @cindex task ID
190 @cindex thread group
191 On Linux, threads created by @code{pthread_create} also receive a
192 @dfn{thread ID}.  The thread ID of the initial (main) thread is the
193 same as the process ID of the entire process.  Thread IDs for
194 subsequently created threads are distinct.  They are allocated from
195 the same numbering space as process IDs.  Process IDs and thread IDs
196 are sometimes also referred to collectively as @dfn{task IDs}.  In
197 contrast to processes, threads are never waited for explicitly, so a
198 thread ID becomes eligible for reuse as soon as a thread exits or is
199 canceled.  This is true even for joinable threads, not just detached
200 threads.  Threads are assigned to a @dfn{thread group}.  In
201 @theglibc{} implementation running on Linux, the process ID is the
202 thread group ID of all threads in the process.
204 You can get the process ID of a process by calling @code{getpid}.  The
205 function @code{getppid} returns the process ID of the parent of the
206 current process (this is also known as the @dfn{parent process ID}).
207 Your program should include the header files @file{unistd.h} and
208 @file{sys/types.h} to use these functions.
209 @pindex sys/types.h
210 @pindex unistd.h
212 @deftp {Data Type} pid_t
213 @standards{POSIX.1, sys/types.h}
214 The @code{pid_t} data type is a signed integer type which is capable
215 of representing a process ID.  In @theglibc{}, this is an @code{int}.
216 @end deftp
218 @deftypefun pid_t getpid (void)
219 @standards{POSIX.1, unistd.h}
220 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
221 The @code{getpid} function returns the process ID of the current process.
222 @end deftypefun
224 @deftypefun pid_t getppid (void)
225 @standards{POSIX.1, unistd.h}
226 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
227 The @code{getppid} function returns the process ID of the parent of the
228 current process.
229 @end deftypefun
231 @deftypefun pid_t gettid (void)
232 @standards{Linux, unistd.h}
233 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
234 The @code{gettid} function returns the thread ID of the current
235 thread.  The returned value is obtained from the Linux kernel and is
236 not subject to caching.  See the discussion of thread IDs above,
237 especially regarding reuse of the IDs of threads which have exited.
239 This function is specific to Linux.
240 @end deftypefun
242 @node Creating a Process
243 @section Creating a Process
245 The @code{fork} function is the primitive for creating a process.
246 It is declared in the header file @file{unistd.h}.
247 @pindex unistd.h
249 @deftypefun pid_t fork (void)
250 @standards{POSIX.1, unistd.h}
251 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuplugin{}}@acunsafe{@aculock{}}}
252 @c The posix/fork.c implementation iterates over the fork_handlers
253 @c using a lock.  It then takes the IO_list lock, resets the thread-local
254 @c pid, and runs fork.  The parent releases the lock, and runs parent
255 @c handlers, and unlocks the internal lock.  The child bumps the fork
256 @c generation, sets the thread-local pid, resets cpu clocks, initializes
257 @c the robust mutex list, the stream locks, the IO_list lock, the dynamic
258 @c loader lock, runs the child handlers, resetting ref counters to 1, and
259 @c initializes the fork lock.  These are all safe, unless atfork
260 @c handlers themselves are unsafe.
261 The @code{fork} function creates a new process.
263 If the operation is successful, there are then both parent and child
264 processes and both see @code{fork} return, but with different values: it
265 returns a value of @code{0} in the child process and returns the child's
266 process ID in the parent process.
268 If process creation failed, @code{fork} returns a value of @code{-1} in
269 the parent process.  The following @code{errno} error conditions are
270 defined for @code{fork}:
272 @table @code
273 @item EAGAIN
274 There aren't enough system resources to create another process, or the
275 user already has too many processes running.  This means exceeding the
276 @code{RLIMIT_NPROC} resource limit, which can usually be increased;
277 @pxref{Limits on Resources}.
279 @item ENOMEM
280 The process requires more space than the system can supply.
281 @end table
282 @end deftypefun
284 The specific attributes of the child process that differ from the
285 parent process are:
287 @itemize @bullet
288 @item
289 The child process has its own unique process ID.
291 @item
292 The parent process ID of the child process is the process ID of its
293 parent process.
295 @item
296 The child process gets its own copies of the parent process's open file
297 descriptors.  Subsequently changing attributes of the file descriptors
298 in the parent process won't affect the file descriptors in the child,
299 and vice versa.  @xref{Control Operations}.  However, the file position
300 associated with each descriptor is shared by both processes;
301 @pxref{File Position}.
303 @item
304 The elapsed processor times for the child process are set to zero;
305 see @ref{Processor Time}.
307 @item
308 The child doesn't inherit file locks set by the parent process.
309 @c !!! flock locks shared
310 @xref{Control Operations}.
312 @item
313 The child doesn't inherit alarms set by the parent process.
314 @xref{Setting an Alarm}.
316 @item
317 The set of pending signals (@pxref{Delivery of Signal}) for the child
318 process is cleared.  (The child process inherits its mask of blocked
319 signals and signal actions from the parent process.)
320 @end itemize
322 @deftypefun pid_t _Fork (void)
323 @standards{GNU, unistd.h}
324 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
325 The @code{_Fork} function is similar to @code{fork}, but it does not invoke
326 any callbacks registered with @code{pthread_atfork}, nor does it reset
327 any internal state or locks (such as the @code{malloc} locks).  In the
328 new subprocess, only async-signal-safe functions may be called, such as
329 @code{dup2} or @code{execve}.
331 The @code{_Fork} function is an async-signal-safe replacement of @code{fork}.
332 It is a GNU extension.
334 @end deftypefun
336 @deftypefun pid_t vfork (void)
337 @standards{BSD, unistd.h}
338 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuplugin{}}@acunsafe{@aculock{}}}
339 @c The vfork implementation proper is a safe syscall, but it may fall
340 @c back to fork if the vfork syscall is not available.
341 The @code{vfork} function is similar to @code{fork} but on some systems
342 it is more efficient; however, there are restrictions you must follow to
343 use it safely.
345 While @code{fork} makes a complete copy of the calling process's address
346 space and allows both the parent and child to execute independently,
347 @code{vfork} does not make this copy.  Instead, the child process
348 created with @code{vfork} shares its parent's address space until it
349 calls @code{_exit} or one of the @code{exec} functions.  In the
350 meantime, the parent process suspends execution.
352 You must be very careful not to allow the child process created with
353 @code{vfork} to modify any global data or even local variables shared
354 with the parent.  Furthermore, the child process cannot return from (or
355 do a long jump out of) the function that called @code{vfork}!  This
356 would leave the parent process's control information very confused.  If
357 in doubt, use @code{fork} instead.
359 Some operating systems don't really implement @code{vfork}.  @Theglibc{}
360 permits you to use @code{vfork} on all systems, but actually
361 executes @code{fork} if @code{vfork} isn't available.  If you follow
362 the proper precautions for using @code{vfork}, your program will still
363 work even if the system uses @code{fork} instead.
364 @end deftypefun
366 @node Querying a Process
367 @section Querying a Process
369 The file descriptor returned by the @code{pidfd_fork} function can be used to
370 query process extra information.
372 @deftypefun pid_t pidfd_getpid (int @var{fd})
373 @standards{GNU, sys/pidfd.h}
374 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
376 The @code{pidfd_getpid} function retrieves the process ID associated with process
377 file descriptor created with @code{pid_spawn}, @code{pidfd_fork}, or
378 @code{pidfd_open}.
380 If the operation fails, @code{pidfd_getpid} return @code{-1} and the following
381 @code{errno} error conditionas are defined:
383 @table @code
384 @item EBADF
385 The input file descriptor is invalid, does not have a pidfd associated, or an
386 error has occurred parsing the kernel data.
387 @item EREMOTE
388 There is no process ID to denote the process in the current namespace.
389 @item ESRCH
390 The process for which the file descriptor refers to is terminated.
391 @item ENOENT
392 The procfs is not mounted.
393 @item ENFILE.
394 Too many open files in system (@code{pidfd_open} tries to open a procfs file and
395 read its contents).
396 @item ENOMEM
397 Insufficient kernel memory was available.
398 @end table
400 This function is specific to Linux.
401 @end deftypefun
403 @node Executing a File
404 @section Executing a File
405 @cindex executing a file
406 @cindex @code{exec} functions
408 This section describes the @code{exec} family of functions, for executing
409 a file as a process image.  You can use these functions to make a child
410 process execute a new program after it has been forked.
412 To see the effects of @code{exec} from the point of view of the called
413 program, see @ref{Program Basics}.
415 @pindex unistd.h
416 The functions in this family differ in how you specify the arguments,
417 but otherwise they all do the same thing.  They are declared in the
418 header file @file{unistd.h}.
420 @deftypefun int execv (const char *@var{filename}, char *const @var{argv}@t{[]})
421 @standards{POSIX.1, unistd.h}
422 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
423 The @code{execv} function executes the file named by @var{filename} as a
424 new process image.
426 The @var{argv} argument is an array of null-terminated strings that is
427 used to provide a value for the @code{argv} argument to the @code{main}
428 function of the program to be executed.  The last element of this array
429 must be a null pointer.  By convention, the first element of this array
430 is the file name of the program sans directory names.  @xref{Program
431 Arguments}, for full details on how programs can access these arguments.
433 The environment for the new process image is taken from the
434 @code{environ} variable of the current process image; see
435 @ref{Environment Variables}, for information about environments.
436 @end deftypefun
438 @deftypefun int execl (const char *@var{filename}, const char *@var{arg0}, @dots{})
439 @standards{POSIX.1, unistd.h}
440 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
441 This is similar to @code{execv}, but the @var{argv} strings are
442 specified individually instead of as an array.  A null pointer must be
443 passed as the last such argument.
444 @end deftypefun
446 @deftypefun int execve (const char *@var{filename}, char *const @var{argv}@t{[]}, char *const @var{env}@t{[]})
447 @standards{POSIX.1, unistd.h}
448 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
449 This is similar to @code{execv}, but permits you to specify the environment
450 for the new program explicitly as the @var{env} argument.  This should
451 be an array of strings in the same format as for the @code{environ}
452 variable; see @ref{Environment Access}.
453 @end deftypefun
455 @deftypefun int fexecve (int @var{fd},  char *const @var{argv}@t{[]}, char *const @var{env}@t{[]})
456 @standards{POSIX.1, unistd.h}
457 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
458 This is similar to @code{execve}, but instead of identifying the program
459 executable by its pathname, the file descriptor @var{fd} is used.  The
460 descriptor must have been opened with the @code{O_RDONLY} flag or (on
461 Linux) the @code{O_PATH} flag.
463 On Linux, @code{fexecve} can fail with an error of @code{ENOSYS} if
464 @file{/proc} has not been mounted and the kernel lacks support for the
465 underlying @code{execveat} system call.
466 @end deftypefun
468 @deftypefun int execle (const char *@var{filename}, const char *@var{arg0}, @dots{}, char *const @var{env}@t{[]})
469 @standards{POSIX.1, unistd.h}
470 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
471 This is similar to @code{execl}, but permits you to specify the
472 environment for the new program explicitly.  The environment argument is
473 passed following the null pointer that marks the last @var{argv}
474 argument, and should be an array of strings in the same format as for
475 the @code{environ} variable.
476 @end deftypefun
478 @deftypefun int execvp (const char *@var{filename}, char *const @var{argv}@t{[]})
479 @standards{POSIX.1, unistd.h}
480 @safety{@prelim{}@mtsafe{@mtsenv{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
481 The @code{execvp} function is similar to @code{execv}, except that it
482 searches the directories listed in the @code{PATH} environment variable
483 (@pxref{Standard Environment}) to find the full file name of a
484 file from @var{filename} if @var{filename} does not contain a slash.
486 This function is useful for executing system utility programs, because
487 it looks for them in the places that the user has chosen.  Shells use it
488 to run the commands that users type.
489 @end deftypefun
491 @deftypefun int execlp (const char *@var{filename}, const char *@var{arg0}, @dots{})
492 @standards{POSIX.1, unistd.h}
493 @safety{@prelim{}@mtsafe{@mtsenv{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
494 This function is like @code{execl}, except that it performs the same
495 file name searching as the @code{execvp} function.
496 @end deftypefun
498 The size of the argument list and environment list taken together must
499 not be greater than @code{ARG_MAX} bytes.  @xref{General Limits}.  On
500 @gnuhurdsystems{}, the size (which compares against @code{ARG_MAX})
501 includes, for each string, the number of characters in the string, plus
502 the size of a @code{char *}, plus one, rounded up to a multiple of the
503 size of a @code{char *}.  Other systems may have somewhat different
504 rules for counting.
506 These functions normally don't return, since execution of a new program
507 causes the currently executing program to go away completely.  A value
508 of @code{-1} is returned in the event of a failure.  In addition to the
509 usual file name errors (@pxref{File Name Errors}), the following
510 @code{errno} error conditions are defined for these functions:
512 @table @code
513 @item E2BIG
514 The combined size of the new program's argument list and environment
515 list is larger than @code{ARG_MAX} bytes.  @gnuhurdsystems{} have no
516 specific limit on the argument list size, so this error code cannot
517 result, but you may get @code{ENOMEM} instead if the arguments are too
518 big for available memory.
520 @item ENOEXEC
521 The specified file can't be executed because it isn't in the right format.
523 @item ENOMEM
524 Executing the specified file requires more storage than is available.
525 @end table
527 If execution of the new file succeeds, it updates the access time field
528 of the file as if the file had been read.  @xref{File Times}, for more
529 details about access times of files.
531 The point at which the file is closed again is not specified, but
532 is at some point before the process exits or before another process
533 image is executed.
535 Executing a new process image completely changes the contents of memory,
536 copying only the argument and environment strings to new locations.  But
537 many other attributes of the process are unchanged:
539 @itemize @bullet
540 @item
541 The process ID and the parent process ID.  @xref{Process Creation Concepts}.
543 @item
544 Session and process group membership.  @xref{Concepts of Job Control}.
546 @item
547 Real user ID and group ID, and supplementary group IDs.  @xref{Process
548 Persona}.
550 @item
551 Pending alarms.  @xref{Setting an Alarm}.
553 @item
554 Current working directory and root directory.  @xref{Working
555 Directory}.  On @gnuhurdsystems{}, the root directory is not copied when
556 executing a setuid program; instead the system default root directory
557 is used for the new program.
559 @item
560 File mode creation mask.  @xref{Setting Permissions}.
562 @item
563 Process signal mask; see @ref{Process Signal Mask}.
565 @item
566 Pending signals; see @ref{Blocking Signals}.
568 @item
569 Elapsed processor time associated with the process; see @ref{Processor Time}.
570 @end itemize
572 If the set-user-ID and set-group-ID mode bits of the process image file
573 are set, this affects the effective user ID and effective group ID
574 (respectively) of the process.  These concepts are discussed in detail
575 in @ref{Process Persona}.
577 Signals that are set to be ignored in the existing process image are
578 also set to be ignored in the new process image.  All other signals are
579 set to the default action in the new process image.  For more
580 information about signals, see @ref{Signal Handling}.
582 File descriptors open in the existing process image remain open in the
583 new process image, unless they have the @code{FD_CLOEXEC}
584 (close-on-exec) flag set.  The files that remain open inherit all
585 attributes of the open file descriptors from the existing process image,
586 including file locks.  File descriptors are discussed in @ref{Low-Level I/O}.
588 Streams, by contrast, cannot survive through @code{exec} functions,
589 because they are located in the memory of the process itself.  The new
590 process image has no streams except those it creates afresh.  Each of
591 the streams in the pre-@code{exec} process image has a descriptor inside
592 it, and these descriptors do survive through @code{exec} (provided that
593 they do not have @code{FD_CLOEXEC} set).  The new process image can
594 reconnect these to new streams using @code{fdopen} (@pxref{Descriptors
595 and Streams}).
597 @node Process Completion
598 @section Process Completion
599 @cindex process completion
600 @cindex waiting for completion of child process
601 @cindex testing exit status of child process
603 The functions described in this section are used to wait for a child
604 process to terminate or stop, and determine its status.  These functions
605 are declared in the header file @file{sys/wait.h}.
606 @pindex sys/wait.h
608 @deftypefun pid_t waitpid (pid_t @var{pid}, int *@var{status-ptr}, int @var{options})
609 @standards{POSIX.1, sys/wait.h}
610 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
611 The @code{waitpid} function is used to request status information from a
612 child process whose process ID is @var{pid}.  Normally, the calling
613 process is suspended until the child process makes status information
614 available by terminating.
616 Other values for the @var{pid} argument have special interpretations.  A
617 value of @code{-1} or @code{WAIT_ANY} requests status information for
618 any child process; a value of @code{0} or @code{WAIT_MYPGRP} requests
619 information for any child process in the same process group as the
620 calling process; and any other negative value @minus{} @var{pgid}
621 requests information for any child process whose process group ID is
622 @var{pgid}.
624 If status information for a child process is available immediately, this
625 function returns immediately without waiting.  If more than one eligible
626 child process has status information available, one of them is chosen
627 randomly, and its status is returned immediately.  To get the status
628 from the other eligible child processes, you need to call @code{waitpid}
629 again.
631 The @var{options} argument is a bit mask.  Its value should be the
632 bitwise OR (that is, the @samp{|} operator) of zero or more of the
633 @code{WNOHANG} and @code{WUNTRACED} flags.  You can use the
634 @code{WNOHANG} flag to indicate that the parent process shouldn't wait;
635 and the @code{WUNTRACED} flag to request status information from stopped
636 processes as well as processes that have terminated.
638 The status information from the child process is stored in the object
639 that @var{status-ptr} points to, unless @var{status-ptr} is a null pointer.
641 This function is a cancellation point in multi-threaded programs.  This
642 is a problem if the thread allocates some resources (like memory, file
643 descriptors, semaphores or whatever) at the time @code{waitpid} is
644 called.  If the thread gets canceled these resources stay allocated
645 until the program ends.  To avoid this calls to @code{waitpid} should be
646 protected using cancellation handlers.
647 @c ref pthread_cleanup_push / pthread_cleanup_pop
649 The return value is normally the process ID of the child process whose
650 status is reported.  If there are child processes but none of them is
651 waiting to be noticed, @code{waitpid} will block until one is.  However,
652 if the @code{WNOHANG} option was specified, @code{waitpid} will return
653 zero instead of blocking.
655 If a specific PID to wait for was given to @code{waitpid}, it will
656 ignore all other children (if any).  Therefore if there are children
657 waiting to be noticed but the child whose PID was specified is not one
658 of them, @code{waitpid} will block or return zero as described above.
660 A value of @code{-1} is returned in case of error.  The following
661 @code{errno} error conditions are defined for this function:
663 @table @code
664 @item EINTR
665 The function was interrupted by delivery of a signal to the calling
666 process.  @xref{Interrupted Primitives}.
668 @item ECHILD
669 There are no child processes to wait for, or the specified @var{pid}
670 is not a child of the calling process.
672 @item EINVAL
673 An invalid value was provided for the @var{options} argument.
674 @end table
675 @end deftypefun
677 These symbolic constants are defined as values for the @var{pid} argument
678 to the @code{waitpid} function.
680 @comment Extra blank lines make it look better.
681 @vtable @code
682 @item WAIT_ANY
684 This constant macro (whose value is @code{-1}) specifies that
685 @code{waitpid} should return status information about any child process.
688 @item WAIT_MYPGRP
689 This constant (with value @code{0}) specifies that @code{waitpid} should
690 return status information about any child process in the same process
691 group as the calling process.
692 @end vtable
694 These symbolic constants are defined as flags for the @var{options}
695 argument to the @code{waitpid} function.  You can bitwise-OR the flags
696 together to obtain a value to use as the argument.
698 @vtable @code
699 @item WNOHANG
701 This flag specifies that @code{waitpid} should return immediately
702 instead of waiting, if there is no child process ready to be noticed.
704 @item WUNTRACED
706 This flag specifies that @code{waitpid} should report the status of any
707 child processes that have been stopped as well as those that have
708 terminated.
709 @end vtable
711 @deftypefun pid_t wait (int *@var{status-ptr})
712 @standards{POSIX.1, sys/wait.h}
713 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
714 This is a simplified version of @code{waitpid}, and is used to wait
715 until any one child process terminates.  The call:
717 @smallexample
718 wait (&status)
719 @end smallexample
721 @noindent
722 is exactly equivalent to:
724 @smallexample
725 waitpid (-1, &status, 0)
726 @end smallexample
728 This function is a cancellation point in multi-threaded programs.  This
729 is a problem if the thread allocates some resources (like memory, file
730 descriptors, semaphores or whatever) at the time @code{wait} is
731 called.  If the thread gets canceled these resources stay allocated
732 until the program ends.  To avoid this calls to @code{wait} should be
733 protected using cancellation handlers.
734 @c ref pthread_cleanup_push / pthread_cleanup_pop
735 @end deftypefun
737 @deftypefun pid_t wait4 (pid_t @var{pid}, int *@var{status-ptr}, int @var{options}, struct rusage *@var{usage})
738 @standards{BSD, sys/wait.h}
739 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
740 If @var{usage} is a null pointer, @code{wait4} is equivalent to
741 @code{waitpid (@var{pid}, @var{status-ptr}, @var{options})}.
743 If @var{usage} is not null, @code{wait4} stores usage figures for the
744 child process in @code{*@var{rusage}} (but only if the child has
745 terminated, not if it has stopped).  @xref{Resource Usage}.
747 This function is a BSD extension.
748 @end deftypefun
750 Here's an example of how to use @code{waitpid} to get the status from
751 all child processes that have terminated, without ever waiting.  This
752 function is designed to be a handler for @code{SIGCHLD}, the signal that
753 indicates that at least one child process has terminated.
755 @smallexample
756 @group
757 void
758 sigchld_handler (int signum)
760   int pid, status, serrno;
761   serrno = errno;
762   while (1)
763     @{
764       pid = waitpid (WAIT_ANY, &status, WNOHANG);
765       if (pid < 0)
766         @{
767           perror ("waitpid");
768           break;
769         @}
770       if (pid == 0)
771         break;
772       notice_termination (pid, status);
773     @}
774   errno = serrno;
776 @end group
777 @end smallexample
779 @node Process Completion Status
780 @section Process Completion Status
782 If the exit status value (@pxref{Program Termination}) of the child
783 process is zero, then the status value reported by @code{waitpid} or
784 @code{wait} is also zero.  You can test for other kinds of information
785 encoded in the returned status value using the following macros.
786 These macros are defined in the header file @file{sys/wait.h}.
787 @pindex sys/wait.h
789 @deftypefn Macro int WIFEXITED (int @var{status})
790 @standards{POSIX.1, sys/wait.h}
791 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
792 This macro returns a nonzero value if the child process terminated
793 normally with @code{exit} or @code{_exit}.
794 @end deftypefn
796 @deftypefn Macro int WEXITSTATUS (int @var{status})
797 @standards{POSIX.1, sys/wait.h}
798 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
799 If @code{WIFEXITED} is true of @var{status}, this macro returns the
800 low-order 8 bits of the exit status value from the child process.
801 @xref{Exit Status}.
802 @end deftypefn
804 @deftypefn Macro int WIFSIGNALED (int @var{status})
805 @standards{POSIX.1, sys/wait.h}
806 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
807 This macro returns a nonzero value if the child process terminated
808 because it received a signal that was not handled.
809 @xref{Signal Handling}.
810 @end deftypefn
812 @deftypefn Macro int WTERMSIG (int @var{status})
813 @standards{POSIX.1, sys/wait.h}
814 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
815 If @code{WIFSIGNALED} is true of @var{status}, this macro returns the
816 signal number of the signal that terminated the child process.
817 @end deftypefn
819 @deftypefn Macro int WCOREDUMP (int @var{status})
820 @standards{BSD, sys/wait.h}
821 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
822 This macro returns a nonzero value if the child process terminated
823 and produced a core dump.
824 @end deftypefn
826 @deftypefn Macro int WIFSTOPPED (int @var{status})
827 @standards{POSIX.1, sys/wait.h}
828 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
829 This macro returns a nonzero value if the child process is stopped.
830 @end deftypefn
832 @deftypefn Macro int WSTOPSIG (int @var{status})
833 @standards{POSIX.1, sys/wait.h}
834 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
835 If @code{WIFSTOPPED} is true of @var{status}, this macro returns the
836 signal number of the signal that caused the child process to stop.
837 @end deftypefn
840 @node BSD Wait Functions
841 @section BSD Process Wait Function
843 @Theglibc{} also provides the @code{wait3} function for compatibility
844 with BSD.  This function is declared in @file{sys/wait.h}.  It is the
845 predecessor to @code{wait4}, which is more flexible.  @code{wait3} is
846 now obsolete.
847 @pindex sys/wait.h
849 @deftypefun pid_t wait3 (int *@var{status-ptr}, int @var{options}, struct rusage *@var{usage})
850 @standards{BSD, sys/wait.h}
851 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
852 If @var{usage} is a null pointer, @code{wait3} is equivalent to
853 @code{waitpid (-1, @var{status-ptr}, @var{options})}.
855 If @var{usage} is not null, @code{wait3} stores usage figures for the
856 child process in @code{*@var{rusage}} (but only if the child has
857 terminated, not if it has stopped).  @xref{Resource Usage}.
858 @end deftypefun
860 @node Process Creation Example
861 @section Process Creation Example
863 Here is an example program showing how you might write a function
864 similar to the built-in @code{system}.  It executes its @var{command}
865 argument using the equivalent of @samp{sh -c @var{command}}.
867 @smallexample
868 #include <stddef.h>
869 #include <stdlib.h>
870 #include <unistd.h>
871 #include <sys/types.h>
872 #include <sys/wait.h>
874 /* @r{Execute the command using this shell program.}  */
875 #define SHELL "/bin/sh"
877 @group
879 my_system (const char *command)
881   int status;
882   pid_t pid;
883 @end group
885   pid = fork ();
886   if (pid == 0)
887     @{
888       /* @r{This is the child process.  Execute the shell command.} */
889       execl (SHELL, SHELL, "-c", command, NULL);
890       _exit (EXIT_FAILURE);
891     @}
892   else if (pid < 0)
893     /* @r{The fork failed.  Report failure.}  */
894     status = -1;
895   else
896     /* @r{This is the parent process.  Wait for the child to complete.}  */
897     if (waitpid (pid, &status, 0) != pid)
898       status = -1;
899   return status;
901 @end smallexample
903 @comment Yes, this example has been tested.
905 There are a couple of things you should pay attention to in this
906 example.
908 Remember that the first @code{argv} argument supplied to the program
909 represents the name of the program being executed.  That is why, in the
910 call to @code{execl}, @code{SHELL} is supplied once to name the program
911 to execute and a second time to supply a value for @code{argv[0]}.
913 The @code{execl} call in the child process doesn't return if it is
914 successful.  If it fails, you must do something to make the child
915 process terminate.  Just returning a bad status code with @code{return}
916 would leave two processes running the original program.  Instead, the
917 right behavior is for the child process to report failure to its parent
918 process.
920 Call @code{_exit} to accomplish this.  The reason for using @code{_exit}
921 instead of @code{exit} is to avoid flushing fully buffered streams such
922 as @code{stdout}.  The buffers of these streams probably contain data
923 that was copied from the parent process by the @code{fork}, data that
924 will be output eventually by the parent process.  Calling @code{exit} in
925 the child would output the data twice.  @xref{Termination Internals}.