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