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