]> git.ipfire.org Git - thirdparty/glibc.git/blame - manual/process.texi
Merge branch release/2.28/master into ibm/2.28/master
[thirdparty/glibc.git] / manual / process.texi
CommitLineData
085d0e35 1@node Processes, Inter-Process Communication, Program Basics, Top
7a68c94a 2@c %MENU% How to create processes and run other programs
28f540f4
RM
3@chapter Processes
4
5@cindex process
6@dfn{Processes} are the primitive units for allocation of system
7resources. Each process has its own address space and (usually) one
8thread of control. A process executes a program; you can have multiple
9processes executing the same program, but each process has its own copy
10of the program within its own address space and executes it
11independently of the other copies.
12
13@cindex child process
14@cindex parent process
15Processes are organized hierarchically. Each process has a @dfn{parent
16process} which explicitly arranged to create it. The processes created
17by a given parent are called its @dfn{child processes}. A child
18inherits many of its attributes from the parent process.
19
20This chapter describes how a program can create, terminate, and control
21child processes. Actually, there are three distinct operations
22involved: creating a new child process, causing the new process to
23execute a program, and coordinating the completion of the child process
24with the original program.
25
26The @code{system} function provides a simple, portable mechanism for
27running another program; it does all three steps automatically. If you
28need more control over the details of how this is done, you can use the
29primitive functions to do each step individually instead.
30
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.
f65fd747 38* Process Completion Status:: How to interpret the status value
28f540f4
RM
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
43
44
45@node Running a Command
46@section Running a Command
47@cindex running a command
48
49The easy way to run another program is to use the @code{system}
50function. This function does all the work of running a subprogram, but
51it doesn't give you much control over the details: you have to wait
52until the subprogram terminates before you can do anything else.
53
28f540f4 54@deftypefun int system (const char *@var{command})
d08a7e4c 55@standards{ISO, stdlib.h}
28f540f4 56@pindex sh
19f5d29c
AO
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 CANCELLATION_P @ascuplugin @ascuheap @acsmem
72@c CANCEL_ENABLED_AND_CANCELED ok
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 CANCEL_ENABLED_AND_CANCELED_AND_ASYNCHRONOUS dup ok
90@c do_cancel dup @ascuplugin @ascuheap @acsmem
91@c LIBC_CANCEL_RESET ok
92@c libc_disable_asynccancel ok
93@c lll_futex_wait dup ok
1f77f049
JM
94This function executes @var{command} as a shell command. In @theglibc{},
95it always uses the default shell @code{sh} to run the command.
28f540f4
RM
96In particular, it searches the directories in @code{PATH} to find
97programs to execute. The return value is @code{-1} if it wasn't
98possible to create the shell process, and otherwise is the status of the
99shell process. @xref{Process Completion}, for details on how this
100status code can be interpreted.
101
bafb8ee9
UD
102If the @var{command} argument is a null pointer, a return value of zero
103indicates that no command processor is available.
cc3fa755 104
0bc93a2f 105This function is a cancellation point in multi-threaded programs. This
dfd2257a
UD
106is a problem if the thread allocates some resources (like memory, file
107descriptors, semaphores or whatever) at the time @code{system} is
108called. If the thread gets canceled these resources stay allocated
109until the program ends. To avoid this calls to @code{system} should be
0bc93a2f 110protected using cancellation handlers.
dfd2257a
UD
111@c ref pthread_cleanup_push / pthread_cleanup_pop
112
28f540f4
RM
113@pindex stdlib.h
114The @code{system} function is declared in the header file
115@file{stdlib.h}.
116@end deftypefun
117
118@strong{Portability Note:} Some C implementations may not have any
119notion of a command processor that can execute other programs. You can
120determine whether a command processor exists by executing
121@w{@code{system (NULL)}}; if the return value is nonzero, a command
122processor is available.
123
124The @code{popen} and @code{pclose} functions (@pxref{Pipe to a
125Subprocess}) are closely related to the @code{system} function. They
126allow the parent process to communicate with the standard input and
127output channels of the command being executed.
128
129@node Process Creation Concepts
130@section Process Creation Concepts
131
132This section gives an overview of processes and of the steps involved in
133creating a process and making it run another program.
134
135@cindex process ID
136@cindex process lifetime
137Each process is named by a @dfn{process ID} number. A unique process ID
138is allocated to each process when it is created. The @dfn{lifetime} of
139a process ends when its termination is reported to its parent process;
140at that time, all of the process resources, including its process ID,
141are freed.
142
143@cindex creating a process
144@cindex forking a process
145@cindex child process
146@cindex parent process
147Processes are created with the @code{fork} system call (so the operation
148of creating a new process is sometimes called @dfn{forking} a process).
149The @dfn{child process} created by @code{fork} is a copy of the original
150@dfn{parent process}, except that it has its own process ID.
151
152After forking a child process, both the parent and child processes
153continue to execute normally. If you want your program to wait for a
154child process to finish executing before continuing, you must do this
155explicitly after the fork operation, by calling @code{wait} or
156@code{waitpid} (@pxref{Process Completion}). These functions give you
157limited information about why the child terminated---for example, its
158exit status code.
159
160A newly forked child process continues to execute the same program as
161its parent process, at the point where the @code{fork} call returns.
162You can use the return value from @code{fork} to tell whether the program
163is running in the parent process or the child.
164
165@cindex process image
166Having several processes run the same program is only occasionally
167useful. But the child can execute another program using one of the
168@code{exec} functions; see @ref{Executing a File}. The program that the
169process is executing is called its @dfn{process image}. Starting
170execution of a new program causes the process to forget all about its
171previous process image; when the new program exits, the process exits
172too, instead of returning to the previous process image.
173
174@node Process Identification
175@section Process Identification
176
177The @code{pid_t} data type represents process IDs. You can get the
178process ID of a process by calling @code{getpid}. The function
179@code{getppid} returns the process ID of the parent of the current
180process (this is also known as the @dfn{parent process ID}). Your
181program should include the header files @file{unistd.h} and
182@file{sys/types.h} to use these functions.
183@pindex sys/types.h
184@pindex unistd.h
185
28f540f4 186@deftp {Data Type} pid_t
d08a7e4c 187@standards{POSIX.1, sys/types.h}
28f540f4 188The @code{pid_t} data type is a signed integer type which is capable
1f77f049 189of representing a process ID. In @theglibc{}, this is an @code{int}.
28f540f4
RM
190@end deftp
191
28f540f4 192@deftypefun pid_t getpid (void)
d08a7e4c 193@standards{POSIX.1, unistd.h}
19f5d29c 194@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
28f540f4
RM
195The @code{getpid} function returns the process ID of the current process.
196@end deftypefun
197
28f540f4 198@deftypefun pid_t getppid (void)
d08a7e4c 199@standards{POSIX.1, unistd.h}
19f5d29c 200@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
28f540f4
RM
201The @code{getppid} function returns the process ID of the parent of the
202current process.
203@end deftypefun
204
205@node Creating a Process
206@section Creating a Process
207
208The @code{fork} function is the primitive for creating a process.
209It is declared in the header file @file{unistd.h}.
210@pindex unistd.h
211
28f540f4 212@deftypefun pid_t fork (void)
d08a7e4c 213@standards{POSIX.1, unistd.h}
19f5d29c
AO
214@safety{@prelim{}@mtsafe{}@asunsafe{@ascuplugin{}}@acunsafe{@aculock{}}}
215@c The nptl/.../linux implementation safely collects fork_handlers into
216@c an alloca()ed linked list and increments ref counters; it uses atomic
217@c ops and retries, avoiding locking altogether. It then takes the
218@c IO_list lock, resets the thread-local pid, and runs fork. The parent
219@c restores the thread-local pid, releases the lock, and runs parent
220@c handlers, decrementing the ref count and signaling futex wait if
221@c requested by unregister_atfork. The child bumps the fork generation,
222@c sets the thread-local pid, resets cpu clocks, initializes the robust
223@c mutex list, the stream locks, the IO_list lock, the dynamic loader
224@c lock, runs the child handlers, reseting ref counters to 1, and
225@c initializes the fork lock. These are all safe, unless atfork
226@c handlers themselves are unsafe.
28f540f4
RM
227The @code{fork} function creates a new process.
228
229If the operation is successful, there are then both parent and child
230processes and both see @code{fork} return, but with different values: it
231returns a value of @code{0} in the child process and returns the child's
232process ID in the parent process.
233
234If process creation failed, @code{fork} returns a value of @code{-1} in
235the parent process. The following @code{errno} error conditions are
236defined for @code{fork}:
237
238@table @code
239@item EAGAIN
240There aren't enough system resources to create another process, or the
241user already has too many processes running. This means exceeding the
242@code{RLIMIT_NPROC} resource limit, which can usually be increased;
243@pxref{Limits on Resources}.
244
245@item ENOMEM
246The process requires more space than the system can supply.
247@end table
248@end deftypefun
249
250The specific attributes of the child process that differ from the
251parent process are:
252
253@itemize @bullet
254@item
255The child process has its own unique process ID.
256
257@item
258The parent process ID of the child process is the process ID of its
259parent process.
260
261@item
262The child process gets its own copies of the parent process's open file
263descriptors. Subsequently changing attributes of the file descriptors
264in the parent process won't affect the file descriptors in the child,
265and vice versa. @xref{Control Operations}. However, the file position
266associated with each descriptor is shared by both processes;
267@pxref{File Position}.
268
269@item
270The elapsed processor times for the child process are set to zero;
271see @ref{Processor Time}.
272
273@item
274The child doesn't inherit file locks set by the parent process.
275@c !!! flock locks shared
276@xref{Control Operations}.
277
278@item
279The child doesn't inherit alarms set by the parent process.
280@xref{Setting an Alarm}.
281
282@item
283The set of pending signals (@pxref{Delivery of Signal}) for the child
284process is cleared. (The child process inherits its mask of blocked
285signals and signal actions from the parent process.)
f65fd747 286@end itemize
28f540f4
RM
287
288
28f540f4 289@deftypefun pid_t vfork (void)
d08a7e4c 290@standards{BSD, unistd.h}
19f5d29c
AO
291@safety{@prelim{}@mtsafe{}@asunsafe{@ascuplugin{}}@acunsafe{@aculock{}}}
292@c The vfork implementation proper is a safe syscall, but it may fall
293@c back to fork if the vfork syscall is not available.
440d13e2
UD
294The @code{vfork} function is similar to @code{fork} but on some systems
295it is more efficient; however, there are restrictions you must follow to
28f540f4
RM
296use it safely.
297
440d13e2
UD
298While @code{fork} makes a complete copy of the calling process's address
299space and allows both the parent and child to execute independently,
300@code{vfork} does not make this copy. Instead, the child process
301created with @code{vfork} shares its parent's address space until it
302calls @code{_exit} or one of the @code{exec} functions. In the
28f540f4
RM
303meantime, the parent process suspends execution.
304
305You must be very careful not to allow the child process created with
306@code{vfork} to modify any global data or even local variables shared
307with the parent. Furthermore, the child process cannot return from (or
308do a long jump out of) the function that called @code{vfork}! This
309would leave the parent process's control information very confused. If
310in doubt, use @code{fork} instead.
311
1f77f049
JM
312Some operating systems don't really implement @code{vfork}. @Theglibc{}
313permits you to use @code{vfork} on all systems, but actually
28f540f4
RM
314executes @code{fork} if @code{vfork} isn't available. If you follow
315the proper precautions for using @code{vfork}, your program will still
316work even if the system uses @code{fork} instead.
317@end deftypefun
318
319@node Executing a File
320@section Executing a File
321@cindex executing a file
322@cindex @code{exec} functions
323
324This section describes the @code{exec} family of functions, for executing
325a file as a process image. You can use these functions to make a child
326process execute a new program after it has been forked.
327
17c389fc 328To see the effects of @code{exec} from the point of view of the called
88197030 329program, see @ref{Program Basics}.
17c389fc 330
28f540f4
RM
331@pindex unistd.h
332The functions in this family differ in how you specify the arguments,
333but otherwise they all do the same thing. They are declared in the
334header file @file{unistd.h}.
335
28f540f4 336@deftypefun int execv (const char *@var{filename}, char *const @var{argv}@t{[]})
d08a7e4c 337@standards{POSIX.1, unistd.h}
19f5d29c 338@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
28f540f4
RM
339The @code{execv} function executes the file named by @var{filename} as a
340new process image.
341
342The @var{argv} argument is an array of null-terminated strings that is
343used to provide a value for the @code{argv} argument to the @code{main}
344function of the program to be executed. The last element of this array
345must be a null pointer. By convention, the first element of this array
346is the file name of the program sans directory names. @xref{Program
347Arguments}, for full details on how programs can access these arguments.
348
349The environment for the new process image is taken from the
350@code{environ} variable of the current process image; see
351@ref{Environment Variables}, for information about environments.
352@end deftypefun
353
28f540f4 354@deftypefun int execl (const char *@var{filename}, const char *@var{arg0}, @dots{})
d08a7e4c 355@standards{POSIX.1, unistd.h}
19f5d29c 356@safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
28f540f4
RM
357This is similar to @code{execv}, but the @var{argv} strings are
358specified individually instead of as an array. A null pointer must be
359passed as the last such argument.
360@end deftypefun
361
28f540f4 362@deftypefun int execve (const char *@var{filename}, char *const @var{argv}@t{[]}, char *const @var{env}@t{[]})
d08a7e4c 363@standards{POSIX.1, unistd.h}
19f5d29c 364@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
28f540f4
RM
365This is similar to @code{execv}, but permits you to specify the environment
366for the new program explicitly as the @var{env} argument. This should
f65fd747 367be an array of strings in the same format as for the @code{environ}
28f540f4
RM
368variable; see @ref{Environment Access}.
369@end deftypefun
370
d1b10e78 371@deftypefun int execle (const char *@var{filename}, const char *@var{arg0}, @dots{}, char *const @var{env}@t{[]})
d08a7e4c 372@standards{POSIX.1, unistd.h}
19f5d29c 373@safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
28f540f4
RM
374This is similar to @code{execl}, but permits you to specify the
375environment for the new program explicitly. The environment argument is
376passed following the null pointer that marks the last @var{argv}
377argument, and should be an array of strings in the same format as for
378the @code{environ} variable.
379@end deftypefun
380
28f540f4 381@deftypefun int execvp (const char *@var{filename}, char *const @var{argv}@t{[]})
d08a7e4c 382@standards{POSIX.1, unistd.h}
19f5d29c 383@safety{@prelim{}@mtsafe{@mtsenv{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
28f540f4
RM
384The @code{execvp} function is similar to @code{execv}, except that it
385searches the directories listed in the @code{PATH} environment variable
386(@pxref{Standard Environment}) to find the full file name of a
387file from @var{filename} if @var{filename} does not contain a slash.
388
389This function is useful for executing system utility programs, because
390it looks for them in the places that the user has chosen. Shells use it
391to run the commands that users type.
392@end deftypefun
393
28f540f4 394@deftypefun int execlp (const char *@var{filename}, const char *@var{arg0}, @dots{})
d08a7e4c 395@standards{POSIX.1, unistd.h}
19f5d29c 396@safety{@prelim{}@mtsafe{@mtsenv{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
28f540f4
RM
397This function is like @code{execl}, except that it performs the same
398file name searching as the @code{execvp} function.
399@end deftypefun
400
401The size of the argument list and environment list taken together must
a7a93d50
JM
402not be greater than @code{ARG_MAX} bytes. @xref{General Limits}. On
403@gnuhurdsystems{}, the size (which compares against @code{ARG_MAX})
28f540f4
RM
404includes, for each string, the number of characters in the string, plus
405the size of a @code{char *}, plus one, rounded up to a multiple of the
406size of a @code{char *}. Other systems may have somewhat different
407rules for counting.
408
409These functions normally don't return, since execution of a new program
410causes the currently executing program to go away completely. A value
411of @code{-1} is returned in the event of a failure. In addition to the
412usual file name errors (@pxref{File Name Errors}), the following
413@code{errno} error conditions are defined for these functions:
414
415@table @code
416@item E2BIG
417The combined size of the new program's argument list and environment
a7a93d50 418list is larger than @code{ARG_MAX} bytes. @gnuhurdsystems{} have no
28f540f4
RM
419specific limit on the argument list size, so this error code cannot
420result, but you may get @code{ENOMEM} instead if the arguments are too
421big for available memory.
422
423@item ENOEXEC
424The specified file can't be executed because it isn't in the right format.
425
426@item ENOMEM
427Executing the specified file requires more storage than is available.
428@end table
429
430If execution of the new file succeeds, it updates the access time field
431of the file as if the file had been read. @xref{File Times}, for more
432details about access times of files.
433
434The point at which the file is closed again is not specified, but
435is at some point before the process exits or before another process
436image is executed.
437
438Executing a new process image completely changes the contents of memory,
439copying only the argument and environment strings to new locations. But
440many other attributes of the process are unchanged:
441
442@itemize @bullet
443@item
444The process ID and the parent process ID. @xref{Process Creation Concepts}.
445
446@item
447Session and process group membership. @xref{Concepts of Job Control}.
448
449@item
450Real user ID and group ID, and supplementary group IDs. @xref{Process
451Persona}.
452
453@item
454Pending alarms. @xref{Setting an Alarm}.
455
456@item
457Current working directory and root directory. @xref{Working
a7a93d50 458Directory}. On @gnuhurdsystems{}, the root directory is not copied when
28f540f4
RM
459executing a setuid program; instead the system default root directory
460is used for the new program.
461
462@item
463File mode creation mask. @xref{Setting Permissions}.
464
465@item
466Process signal mask; see @ref{Process Signal Mask}.
467
468@item
469Pending signals; see @ref{Blocking Signals}.
470
471@item
472Elapsed processor time associated with the process; see @ref{Processor Time}.
473@end itemize
474
475If the set-user-ID and set-group-ID mode bits of the process image file
476are set, this affects the effective user ID and effective group ID
477(respectively) of the process. These concepts are discussed in detail
478in @ref{Process Persona}.
479
480Signals that are set to be ignored in the existing process image are
481also set to be ignored in the new process image. All other signals are
482set to the default action in the new process image. For more
483information about signals, see @ref{Signal Handling}.
484
485File descriptors open in the existing process image remain open in the
486new process image, unless they have the @code{FD_CLOEXEC}
487(close-on-exec) flag set. The files that remain open inherit all
9cbcfebd 488attributes of the open file descriptors from the existing process image,
28f540f4
RM
489including file locks. File descriptors are discussed in @ref{Low-Level I/O}.
490
491Streams, by contrast, cannot survive through @code{exec} functions,
492because they are located in the memory of the process itself. The new
493process image has no streams except those it creates afresh. Each of
494the streams in the pre-@code{exec} process image has a descriptor inside
495it, and these descriptors do survive through @code{exec} (provided that
496they do not have @code{FD_CLOEXEC} set). The new process image can
497reconnect these to new streams using @code{fdopen} (@pxref{Descriptors
498and Streams}).
499
500@node Process Completion
501@section Process Completion
502@cindex process completion
503@cindex waiting for completion of child process
504@cindex testing exit status of child process
505
506The functions described in this section are used to wait for a child
507process to terminate or stop, and determine its status. These functions
508are declared in the header file @file{sys/wait.h}.
509@pindex sys/wait.h
510
28f540f4 511@deftypefun pid_t waitpid (pid_t @var{pid}, int *@var{status-ptr}, int @var{options})
d08a7e4c 512@standards{POSIX.1, sys/wait.h}
19f5d29c 513@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
28f540f4
RM
514The @code{waitpid} function is used to request status information from a
515child process whose process ID is @var{pid}. Normally, the calling
516process is suspended until the child process makes status information
517available by terminating.
518
519Other values for the @var{pid} argument have special interpretations. A
520value of @code{-1} or @code{WAIT_ANY} requests status information for
521any child process; a value of @code{0} or @code{WAIT_MYPGRP} requests
522information for any child process in the same process group as the
523calling process; and any other negative value @minus{} @var{pgid}
524requests information for any child process whose process group ID is
525@var{pgid}.
526
527If status information for a child process is available immediately, this
528function returns immediately without waiting. If more than one eligible
529child process has status information available, one of them is chosen
530randomly, and its status is returned immediately. To get the status
531from the other eligible child processes, you need to call @code{waitpid}
532again.
533
534The @var{options} argument is a bit mask. Its value should be the
535bitwise OR (that is, the @samp{|} operator) of zero or more of the
536@code{WNOHANG} and @code{WUNTRACED} flags. You can use the
537@code{WNOHANG} flag to indicate that the parent process shouldn't wait;
538and the @code{WUNTRACED} flag to request status information from stopped
539processes as well as processes that have terminated.
540
541The status information from the child process is stored in the object
542that @var{status-ptr} points to, unless @var{status-ptr} is a null pointer.
543
0bc93a2f 544This function is a cancellation point in multi-threaded programs. This
dfd2257a
UD
545is a problem if the thread allocates some resources (like memory, file
546descriptors, semaphores or whatever) at the time @code{waitpid} is
547called. If the thread gets canceled these resources stay allocated
548until the program ends. To avoid this calls to @code{waitpid} should be
0bc93a2f 549protected using cancellation handlers.
dfd2257a
UD
550@c ref pthread_cleanup_push / pthread_cleanup_pop
551
28f540f4 552The return value is normally the process ID of the child process whose
3c20b9b6
UD
553status is reported. If there are child processes but none of them is
554waiting to be noticed, @code{waitpid} will block until one is. However,
555if the @code{WNOHANG} option was specified, @code{waitpid} will return
556zero instead of blocking.
557
558If a specific PID to wait for was given to @code{waitpid}, it will
559ignore all other children (if any). Therefore if there are children
560waiting to be noticed but the child whose PID was specified is not one
561of them, @code{waitpid} will block or return zero as described above.
562
563A value of @code{-1} is returned in case of error. The following
564@code{errno} error conditions are defined for this function:
28f540f4
RM
565
566@table @code
567@item EINTR
568The function was interrupted by delivery of a signal to the calling
569process. @xref{Interrupted Primitives}.
570
571@item ECHILD
572There are no child processes to wait for, or the specified @var{pid}
573is not a child of the calling process.
574
575@item EINVAL
576An invalid value was provided for the @var{options} argument.
577@end table
578@end deftypefun
579
580These symbolic constants are defined as values for the @var{pid} argument
581to the @code{waitpid} function.
582
583@comment Extra blank lines make it look better.
2fe82ca6 584@vtable @code
28f540f4
RM
585@item WAIT_ANY
586
587This constant macro (whose value is @code{-1}) specifies that
588@code{waitpid} should return status information about any child process.
589
590
591@item WAIT_MYPGRP
592This constant (with value @code{0}) specifies that @code{waitpid} should
593return status information about any child process in the same process
594group as the calling process.
2fe82ca6 595@end vtable
28f540f4
RM
596
597These symbolic constants are defined as flags for the @var{options}
598argument to the @code{waitpid} function. You can bitwise-OR the flags
599together to obtain a value to use as the argument.
600
2fe82ca6 601@vtable @code
28f540f4
RM
602@item WNOHANG
603
604This flag specifies that @code{waitpid} should return immediately
605instead of waiting, if there is no child process ready to be noticed.
606
607@item WUNTRACED
608
609This flag specifies that @code{waitpid} should report the status of any
610child processes that have been stopped as well as those that have
611terminated.
2fe82ca6 612@end vtable
28f540f4 613
28f540f4 614@deftypefun pid_t wait (int *@var{status-ptr})
d08a7e4c 615@standards{POSIX.1, sys/wait.h}
19f5d29c 616@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
28f540f4
RM
617This is a simplified version of @code{waitpid}, and is used to wait
618until any one child process terminates. The call:
619
620@smallexample
621wait (&status)
622@end smallexample
623
624@noindent
625is exactly equivalent to:
626
627@smallexample
628waitpid (-1, &status, 0)
629@end smallexample
dfd2257a 630
0bc93a2f 631This function is a cancellation point in multi-threaded programs. This
dfd2257a
UD
632is a problem if the thread allocates some resources (like memory, file
633descriptors, semaphores or whatever) at the time @code{wait} is
634called. If the thread gets canceled these resources stay allocated
635until the program ends. To avoid this calls to @code{wait} should be
0bc93a2f 636protected using cancellation handlers.
dfd2257a 637@c ref pthread_cleanup_push / pthread_cleanup_pop
28f540f4
RM
638@end deftypefun
639
28f540f4 640@deftypefun pid_t wait4 (pid_t @var{pid}, int *@var{status-ptr}, int @var{options}, struct rusage *@var{usage})
d08a7e4c 641@standards{BSD, sys/wait.h}
19f5d29c 642@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
28f540f4
RM
643If @var{usage} is a null pointer, @code{wait4} is equivalent to
644@code{waitpid (@var{pid}, @var{status-ptr}, @var{options})}.
645
646If @var{usage} is not null, @code{wait4} stores usage figures for the
647child process in @code{*@var{rusage}} (but only if the child has
648terminated, not if it has stopped). @xref{Resource Usage}.
649
650This function is a BSD extension.
651@end deftypefun
652
653Here's an example of how to use @code{waitpid} to get the status from
654all child processes that have terminated, without ever waiting. This
655function is designed to be a handler for @code{SIGCHLD}, the signal that
656indicates that at least one child process has terminated.
657
658@smallexample
659@group
660void
661sigchld_handler (int signum)
662@{
f9d6455b
UD
663 int pid, status, serrno;
664 serrno = errno;
28f540f4
RM
665 while (1)
666 @{
667 pid = waitpid (WAIT_ANY, &status, WNOHANG);
668 if (pid < 0)
669 @{
670 perror ("waitpid");
671 break;
672 @}
673 if (pid == 0)
674 break;
675 notice_termination (pid, status);
676 @}
f9d6455b 677 errno = serrno;
28f540f4
RM
678@}
679@end group
680@end smallexample
681
682@node Process Completion Status
683@section Process Completion Status
684
685If the exit status value (@pxref{Program Termination}) of the child
686process is zero, then the status value reported by @code{waitpid} or
687@code{wait} is also zero. You can test for other kinds of information
688encoded in the returned status value using the following macros.
689These macros are defined in the header file @file{sys/wait.h}.
690@pindex sys/wait.h
691
28f540f4 692@deftypefn Macro int WIFEXITED (int @var{status})
d08a7e4c 693@standards{POSIX.1, sys/wait.h}
19f5d29c 694@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
28f540f4
RM
695This macro returns a nonzero value if the child process terminated
696normally with @code{exit} or @code{_exit}.
697@end deftypefn
698
28f540f4 699@deftypefn Macro int WEXITSTATUS (int @var{status})
d08a7e4c 700@standards{POSIX.1, sys/wait.h}
19f5d29c 701@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
28f540f4
RM
702If @code{WIFEXITED} is true of @var{status}, this macro returns the
703low-order 8 bits of the exit status value from the child process.
704@xref{Exit Status}.
705@end deftypefn
706
28f540f4 707@deftypefn Macro int WIFSIGNALED (int @var{status})
d08a7e4c 708@standards{POSIX.1, sys/wait.h}
19f5d29c 709@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
28f540f4
RM
710This macro returns a nonzero value if the child process terminated
711because it received a signal that was not handled.
712@xref{Signal Handling}.
713@end deftypefn
714
28f540f4 715@deftypefn Macro int WTERMSIG (int @var{status})
d08a7e4c 716@standards{POSIX.1, sys/wait.h}
19f5d29c 717@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
28f540f4
RM
718If @code{WIFSIGNALED} is true of @var{status}, this macro returns the
719signal number of the signal that terminated the child process.
720@end deftypefn
721
28f540f4 722@deftypefn Macro int WCOREDUMP (int @var{status})
d08a7e4c 723@standards{BSD, sys/wait.h}
19f5d29c 724@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
28f540f4
RM
725This macro returns a nonzero value if the child process terminated
726and produced a core dump.
727@end deftypefn
728
28f540f4 729@deftypefn Macro int WIFSTOPPED (int @var{status})
d08a7e4c 730@standards{POSIX.1, sys/wait.h}
19f5d29c 731@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
28f540f4
RM
732This macro returns a nonzero value if the child process is stopped.
733@end deftypefn
734
28f540f4 735@deftypefn Macro int WSTOPSIG (int @var{status})
d08a7e4c 736@standards{POSIX.1, sys/wait.h}
19f5d29c 737@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
28f540f4
RM
738If @code{WIFSTOPPED} is true of @var{status}, this macro returns the
739signal number of the signal that caused the child process to stop.
740@end deftypefn
741
742
743@node BSD Wait Functions
b49ab5f4 744@section BSD Process Wait Function
28f540f4 745
b49ab5f4
FW
746@Theglibc{} also provides the @code{wait3} function for compatibility
747with BSD. This function is declared in @file{sys/wait.h}. It is the
748predecessor to @code{wait4}, which is more flexible. @code{wait3} is
749now obsolete.
28f540f4
RM
750@pindex sys/wait.h
751
b49ab5f4 752@deftypefun pid_t wait3 (int *@var{status-ptr}, int @var{options}, struct rusage *@var{usage})
d08a7e4c 753@standards{BSD, sys/wait.h}
19f5d29c 754@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
28f540f4
RM
755If @var{usage} is a null pointer, @code{wait3} is equivalent to
756@code{waitpid (-1, @var{status-ptr}, @var{options})}.
757
758If @var{usage} is not null, @code{wait3} stores usage figures for the
759child process in @code{*@var{rusage}} (but only if the child has
760terminated, not if it has stopped). @xref{Resource Usage}.
761@end deftypefun
762
763@node Process Creation Example
764@section Process Creation Example
765
766Here is an example program showing how you might write a function
767similar to the built-in @code{system}. It executes its @var{command}
768argument using the equivalent of @samp{sh -c @var{command}}.
769
770@smallexample
771#include <stddef.h>
772#include <stdlib.h>
773#include <unistd.h>
774#include <sys/types.h>
775#include <sys/wait.h>
776
777/* @r{Execute the command using this shell program.} */
778#define SHELL "/bin/sh"
779
780@group
f65fd747 781int
28f540f4
RM
782my_system (const char *command)
783@{
784 int status;
785 pid_t pid;
786@end group
787
788 pid = fork ();
789 if (pid == 0)
790 @{
791 /* @r{This is the child process. Execute the shell command.} */
792 execl (SHELL, SHELL, "-c", command, NULL);
793 _exit (EXIT_FAILURE);
794 @}
795 else if (pid < 0)
796 /* @r{The fork failed. Report failure.} */
797 status = -1;
798 else
799 /* @r{This is the parent process. Wait for the child to complete.} */
800 if (waitpid (pid, &status, 0) != pid)
801 status = -1;
802 return status;
803@}
804@end smallexample
805
806@comment Yes, this example has been tested.
807
808There are a couple of things you should pay attention to in this
809example.
810
811Remember that the first @code{argv} argument supplied to the program
812represents the name of the program being executed. That is why, in the
813call to @code{execl}, @code{SHELL} is supplied once to name the program
f65fd747 814to execute and a second time to supply a value for @code{argv[0]}.
28f540f4
RM
815
816The @code{execl} call in the child process doesn't return if it is
817successful. If it fails, you must do something to make the child
818process terminate. Just returning a bad status code with @code{return}
819would leave two processes running the original program. Instead, the
820right behavior is for the child process to report failure to its parent
821process.
822
823Call @code{_exit} to accomplish this. The reason for using @code{_exit}
824instead of @code{exit} is to avoid flushing fully buffered streams such
825as @code{stdout}. The buffers of these streams probably contain data
826that was copied from the parent process by the @code{fork}, data that
827will be output eventually by the parent process. Calling @code{exit} in
828the child would output the data twice. @xref{Termination Internals}.