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