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