Sun Dec 17 15:56:35 1995 Miles Bader <miles@gnu.ai.mit.edu>
[glibc.git] / manual / =process.texinfo
blob63c723ed37469d854abf464f26ead0c211b4007c
1 @node Processes, Job Control, Signal Handling, Top
2 @chapter Processes
4 @cindex process
5 @dfn{Processes} are the primitive units for allocation of system
6 resources.  Each process has its own address space and (usually) one
7 thread of control.  A process executes a program; you can have multiple
8 processes executing the same program, but each process has its own copy
9 of the program within its own address space and executes it
10 independently of the other copies.
12 Processes are organized hierarchically.  Child processes are created by
13 a parent process, and inherit many of their attributes from the parent
14 process.
16 This chapter describes how a program can create, terminate, and control
17 child processes.
19 @menu
20 * Program Arguments::           Parsing the command-line arguments to
21                                  a program.
22 * Environment Variables::       How to access parameters inherited from
23                                  a parent process.
24 * Program Termination::         How to cause a process to terminate and
25                                  return status information to its parent.
26 * Creating New Processes::      Running other programs.
27 @end menu
30 @node Program Arguments, Environment Variables,  , Processes
31 @section Program Arguments
32 @cindex program arguments
33 @cindex command line arguments
35 @cindex @code{main} function
36 When your C program starts, it begins by executing the function called
37 @code{main}.  You can define @code{main} either to take no arguments,
38 or to take two arguments that represent the command line arguments
39 to the program, like this:
41 @example
42 int main (int @var{argc}, char *@var{argv}[])
43 @end example
45 @cindex argc (program argument count)
46 @cindex argv (program argument vector)
47 The command line arguments are the whitespace-separated tokens typed by
48 the user to the shell in invoking the program.  The value of the
49 @var{argc} argument is the number of command line arguments.  The
50 @var{argv} argument is a vector of pointers to @code{char}; sometimes it
51 is also declared as @samp{char **@var{argv}}.  The elements of
52 @var{argv} are the individual command line argument strings.  By
53 convention, @code{@var{argv}[0]} is the file name of the program being
54 run, and @code{@var{argv}[@var{argc}]} is a null pointer.
56 If the syntax for the command line arguments to your program is simple
57 enough, you can simply pick the arguments off from @var{argv} by hand.
58 But unless your program takes a fixed number of arguments, or all of the
59 arguments are interpreted in the same way (as file names, for example),
60 you are usually better off using @code{getopt} to do the parsing.
62 @menu
63 * Argument Syntax Conventions::  By convention, program
64                                                  options are specified by a
65                                                  leading hyphen.
66 * Parsing Program Arguments::   The @code{getopt} function.
67 * Example Using getopt::  An example of @code{getopt}.
68 @end menu
70 @node Argument Syntax Conventions, Parsing Program Arguments,  , Program Arguments
71 @subsection Program Argument Syntax Conventions
72 @cindex program argument syntax
73 @cindex syntax, for program arguments
74 @cindex command argument syntax
76 The @code{getopt} function decodes options following the usual
77 conventions for POSIX utilities:
79 @itemize @bullet
80 @item
81 Arguments are options if they begin with a hyphen delimiter (@samp{-}).
83 @item
84 Multiple options may follow a hyphen delimiter in a single token if
85 the options do not take arguments.  Thus, @samp{-abc} is equivalent to
86 @samp{-a -b -c}.
88 @item
89 Option names are single alphanumeric (as for @code{isalnum};
90 see @ref{Classification of Characters}).
92 @item
93 Certain options require an argument.  For example, the @samp{-o} 
94 command of the ld command requires an argument---an output file name.
96 @item
97 An option and its argument may or may appear as separate tokens.  (In
98 other words, the whitespace separating them is optional.)  Thus,
99 @samp{-o foo} and @samp{-ofoo} are equivalent.
101 @item
102 Options typically precede other non-option arguments.
104 The implementation of @code{getopt} in the GNU C library normally makes
105 it appear as if all the option arguments were specified before all the
106 non-option arguments for the purposes of parsing, even if the user of
107 your program intermixed option and non-option arguments.  It does this
108 by reordering the elements of the @var{argv} array.  This behavior is
109 nonstandard; if you want to suppress it, define the
110 @code{_POSIX_OPTION_ORDER} environment variable.  @xref{Standard
111 Environment Variables}.
113 @item
114 The argument @samp{--} terminates all options; any following arguments
115 are treated as non-option arguments, even if they begin with a hyphen.
117 @item
118 A token consisting of a single hyphen character is interpreted as an
119 ordinary non-option argument.  By convention, it is used to specify
120 input from or output to the standard input and output streams.
122 @item
123 Options may be supplied in any order, or appear multiple times.  The
124 interpretation is left up to the particular application program.
125 @end itemize
127 @node Parsing Program Arguments, Example Using getopt, Argument Syntax Conventions, Program Arguments
128 @subsection Parsing Program Arguments
129 @cindex program arguments, parsing
130 @cindex command arguments, parsing
131 @cindex parsing program arguments
133 Here are the details about how to call the @code{getopt} function.  To
134 use this facility, your program must include the header file
135 @file{unistd.h}.
136 @pindex unistd.h
138 @comment unistd.h
139 @comment POSIX.2
140 @deftypevar int opterr
141 If the value of this variable is nonzero, then @code{getopt} prints an
142 error message to the standard error stream if it encounters an unknown
143 option character or an option with a missing required argument.  This is
144 the default behavior.  If you set this variable to zero, @code{getopt}
145 does not print any messages, but it still returns @code{?} to indicate
146 an error.
147 @end deftypevar
149 @comment unistd.h
150 @comment POSIX.2
151 @deftypevar int optopt
152 When @code{getopt} encounters an unknown option character or an option
153 with a missing required argument, it stores that option character in
154 this variable.  You can use this for providing your own diagnostic
155 messages.
156 @end deftypevar
158 @comment unistd.h
159 @comment POSIX.2
160 @deftypevar int optind
161 This variable is set by @code{getopt} to the index of the next element
162 of the @var{argv} array to be processed.  Once @code{getopt} has found
163 all of the option arguments, you can use this variable to determine
164 where the remaining non-option arguments begin.  The initial value of
165 this variable is @code{1}.
166 @end deftypevar
168 @comment unistd.h
169 @comment POSIX.2
170 @deftypevar {char *} optarg
171 This variable is set by @code{getopt} to point at the value of the
172 option argument, for those options that accept arguments.
173 @end deftypevar
175 @comment unistd.h
176 @comment POSIX.2
177 @deftypefun int getopt (int @var{argc}, char **@var{argv}, const char *@var{options})
178 The @code{getopt} function gets the next option argument from the
179 argument list specified by the @var{argv} and @var{argc} arguments.
180 Normally these arguments' values come directly from the arguments of
181 @code{main}.
183 The @var{options} argument is a string that specifies the option
184 characters that are valid for this program.  An option character in this
185 string can be followed by a colon (@samp{:}) to indicate that it takes a
186 required argument.
188 If the @var{options} argument string begins with a hyphen (@samp{-}), this
189 is treated specially.  It permits arguments without an option to be
190 returned as if they were associated with option character @samp{\0}.
192 The @code{getopt} function returns the option character for the next
193 command line option.  When no more option arguments are available, it
194 returns @code{-1}.  There may still be more non-option arguments; you
195 must compare the external variable @code{optind} against the @var{argv}
196 parameter to check this.
198 If the options has an argument, @code{getopt} returns the argument by
199 storing it in the varables @var{optarg}.  You don't ordinarily need to
200 copy the @code{optarg} string, since it is a pointer into the original
201 @var{argv} array, not into a static area that might be overwritten.
203 If @code{getopt} finds an option character in @var{argv} that was not
204 included in @var{options}, or a missing option argument, it returns
205 @samp{?} and sets the external variable @code{optopt} to the actual
206 option character.  In addition, if the external variable @code{opterr}
207 is nonzero, @code{getopt} prints an error message.
208 @end deftypefun
210 @node Example Using getopt,  , Parsing Program Arguments, Program Arguments
211 @subsection Example of Parsing Program Arguments
213 Here is an example showing how @code{getopt} is typically used.  The
214 key points to notice are:
216 @itemize @bullet
217 @item
218 Normally, @code{getopt} is called in a loop.  When @code{getopt} returns
219 @code{-1}, indicating no more options are present, the loop terminates.
221 @item
222 A @code{switch} statement is used to dispatch on the return value from
223 @code{getopt}.  In typical use, each case just sets a variable that
224 is used later in the program.
226 @item
227 A second loop is used to process the remaining non-option arguments.
228 @end itemize
230 @example
231 @include testopt.c.texi
232 @end example
234 Here are some examples showing what this program prints with different
235 combinations of arguments:
237 @example
238 % testopt
239 aflag = 0, bflag = 0, cvalue = (null)
241 % testopt -a -b
242 aflag = 1, bflag = 1, cvalue = (null)
244 % testopt -ab
245 aflag = 1, bflag = 1, cvalue = (null)
247 % testopt -c foo
248 aflag = 0, bflag = 0, cvalue = foo
250 % testopt -cfoo
251 aflag = 0, bflag = 0, cvalue = foo
253 % testopt arg1
254 aflag = 0, bflag = 0, cvalue = (null)
255 Non-option argument arg1
257 % testopt -a arg1
258 aflag = 1, bflag = 0, cvalue = (null)
259 Non-option argument arg1
261 % testopt -c foo arg1
262 aflag = 0, bflag = 0, cvalue = foo
263 Non-option argument arg1
265 % testopt -a -- -b
266 aflag = 1, bflag = 0, cvalue = (null)
267 Non-option argument -b
269 % testopt -a -
270 aflag = 1, bflag = 0, cvalue = (null)
271 Non-option argument -
272 @end example
274 @node Environment Variables, Program Termination, Program Arguments, Processes
275 @section Environment Variables
277 @cindex environment variable
278 When a program is executed, it receives information about the context in
279 which it was invoked in two ways.  The first mechanism uses the
280 @var{argv} and @var{argc} arguments to its @code{main} function, and is
281 discussed in @ref{Program Arguments}.  The second mechanism is
282 uses @dfn{environment variables} and is discussed in this section.
284 The @var{argv} mechanism is typically used to pass command-line
285 arguments specific to the particular program being invoked.  The
286 environment, on the other hand, keeps track of information that is
287 shared by many programs, changes infrequently, and that is less
288 frequently accessed.
290 The environment variables discussed in this section are the same
291 environment variables that you set using the assignments and the
292 @code{export} command in the shell.  Programs executed from the shell
293 inherit all of the environment variables from the shell.
295 @cindex environment
296 Standard environment variables are used for information about the user's
297 home directory, terminal type, current locale, and so on; you can define
298 additional variables for other purposes.  The set of all environment
299 variables that have values is collectively known as the
300 @dfn{environment}.
302 Names of environment variables are case-sensitive and must not contain
303 the character @samp{=}.  System-defined environment variables are
304 invariably uppercase.
306 The values of environment variables can be anything that can be
307 represented as a string.  A value must not contain an embedded null
308 character, since this is assumed to terminate the string.
311 @menu
312 * Environment Access::          How to get and set the values of
313                                          environment variables.
314 * Standard Environment Variables::  These environment variables have
315                                          standard interpretations.
316 @end menu
318 @node Environment Access, Standard Environment Variables,  , Environment Variables
319 @subsection Environment Access
320 @cindex environment access
321 @cindex environment representation
323 The value of an environment variable can be accessed with the
324 @code{getenv} function.  This is declared in the header file
325 @file{stdlib.h}.
326 @pindex stdlib.h
328 @comment stdlib.h
329 @comment ANSI
330 @deftypefun {char *} getenv (const char *@var{name})
331 This function returns a string that is the value of the environment
332 variable @var{name}.  You must not modify this string.  In some systems
333 not using the GNU library, it might be overwritten by subsequent calls
334 to @code{getenv} (but not by any other library function).  If the
335 environment variable @var{name} is not defined, the value is a null
336 pointer.
337 @end deftypefun
340 @comment stdlib.h
341 @comment SVID
342 @deftypefun int putenv (const char *@var{string})
343 The @code{putenv} function adds or removes definitions from the environment.
344 If the @var{string} is of the form @samp{@var{name}=@var{value}}, the
345 definition is added to the environment.  Otherwise, the @var{string} is
346 interpreted as the name of an environment variable, and any definition
347 for this variable in the environment is removed.
349 The GNU library provides this function for compatibility with SVID; it
350 may not be available in other systems.
351 @end deftypefun
353 You can deal directly with the underlying representation of environment
354 objects to add more variables to the environment (for example, to
355 communicate with another program you are about to execute; see
356 @ref{Executing a File}).  
358 @comment unistd.h
359 @comment POSIX.1
360 @deftypevar {char **} environ
361 The environment is represented as an array of strings.  Each string is
362 of the format @samp{@var{name}=@var{value}}.  The order in which
363 strings appear in the environment is not significant, but the same
364 @var{name} must not appear more than once.  The last element of the
365 array is a null pointer.
367 This variable is not declared in any header file, but if you declare it
368 in your own program as @code{extern}, the right thing will happen.
370 If you just want to get the value of an environment variable, use
371 @code{getenv}.
372 @end deftypevar
374 @node Standard Environment Variables,  , Environment Access, Environment Variables
375 @subsection Standard Environment Variables
376 @cindex standard environment variables
378 These environment variables have standard meanings.
379 This doesn't mean that they are always present in the
380 environment, though; it just means that if these variables @emph{are}
381 present, they have these meanings, and that you shouldn't try to use
382 these environment variable names for some other purpose.
384 @table @code
385 @item HOME
386 @cindex HOME environment variable
387 @cindex home directory
388 This is a string representing the user's @dfn{home directory}, or
389 initial default working directory.  @xref{User Database}, for a
390 more secure way of determining this information.
392 @comment RMS says to explay why HOME is better, but I don't know why.
394 @item LOGNAME
395 @cindex LOGNAME environment variable
396 This is the name that the user used to log in.  Since the value in the
397 environment can be tweaked arbitrarily, this is not a reliable way to
398 identify the user who is running a process; a function like
399 @code{getlogin} (@pxref{User Identification Functions}) is better for
400 that purpose.
402 @comment RMS says to explay why LOGNAME is better, but I don't know why.
404 @item PATH
405 @cindex PATH environment variable
406 A @dfn{path} is a sequence of directory names which is used for
407 searching for a file.  The variable @var{PATH} holds a path The
408 @code{execlp} and @code{execvp} functions (@pxref{Executing a File})
409 uses this environment variable, as do many shells and other utilities
410 which are implemented in terms of those functions.
412 The syntax of a path is a sequence of directory names separated by
413 colons.  An empty string instead of a directory name stands for the 
414 current directory.  (@xref{Working Directory}.)
416 A typical value for this environment variable might be a string like:
418 @example
419 .:/bin:/etc:/usr/bin:/usr/new/X11:/usr/new:/usr/local:/usr/local/bin
420 @end example
422 This means that if the user tries to execute a program named @code{foo},
423 the system will look for files named @file{./foo}, @file{/bin/foo},
424 @file{/etc/foo}, and so on.  The first of these files that exists is
425 the one that is executed.
427 @item TERM
428 @cindex TERM environment variable
429 This specifies the kind of terminal that is receiving program output.
430 Some programs can make use of this information to take advantage of
431 special escape sequences or terminal modes supported by particular kinds
432 of terminals.  Many programs which use the termcap library
433 (@pxref{Finding a Terminal Description,Find,,termcap,The Termcap Library
434 Manual}) use the @code{TERM} environment variable, for example.
436 @item TZ
437 @cindex TZ environment variable
438 This specifies the time zone.  @xref{Time Zone}, for information about
439 the format of this string and how it is used.
441 @item LANG
442 @cindex LANG environment variable
443 This specifies the default locale to use for attribute categories where
444 neither @code{LC_ALL} nor the specific environment variable for that
445 category is set.  @xref{Locales}, for more information about
446 locales.
448 @item LC_ALL
449 @cindex LC_ALL environment variable
450 This is similar to the @code{LANG} environment variable.  However, its
451 value takes precedence over any values provided for the individual
452 attribute category environment variables, or for the @code{LANG}
453 environment variable.
455 @item LC_COLLATE
456 @cindex LC_COLLATE environment variable
457 This specifies what locale to use for string sorting.
459 @item LC_CTYPE
460 @cindex LC_CTYPE environment variable
461 This specifies what locale to use for character sets and character
462 classification.
464 @item LC_MONETARY
465 @cindex LC_MONETARY environment variable
466 This specifies what locale to use for formatting monetary values.
468 @item LC_NUMERIC
469 @cindex LC_NUMERIC environment variable
470 This specifies what locale to use for formatting numbers.
472 @item LC_TIME
473 @cindex LC_TIME environment variable
474 This specifies what locale to use for formatting date/time values.
476 @item _POSIX_OPTION_ORDER
477 @cindex _POSIX_OPTION_ORDER environment variable.
478 If this environment variable is defined, it suppresses the usual
479 reordering of command line arguments by @code{getopt}.  @xref{Program
480 Argument Syntax Conventions}.
481 @end table
483 @node Program Termination, Creating New Processes, Environment Variables, Processes
484 @section Program Termination
485 @cindex program termination
486 @cindex process termination
488 @cindex exit status value
489 The usual way for a program to terminate is simply for its @code{main}
490 function to return.  The @dfn{exit status value} returned from the
491 @code{main} function is used to report information back to the process's
492 parent process or shell.
494 A program can also terminate normally calling the @code{exit}
495 function
497 In addition, programs can be terminated by signals; this is discussed in
498 more detail in @ref{Signal Handling}.  The @code{abort} function causes
499 a terminal that kills the program.
501 @menu
502 * Normal Program Termination::  
503 * Exit Status::                 Exit Status
504 * Cleanups on Exit::            Cleanups on Exit
505 * Aborting a Program::          
506 * Termination Internals::       Termination Internals
507 @end menu
509 @node Normal Program Termination, Exit Status,  , Program Termination
510 @subsection Normal Program Termination
512 @comment stdlib.h
513 @comment ANSI
514 @deftypefun void exit (int @var{status})
515 The @code{exit} function causes normal program termination with status
516 @var{status}.  This function does not return.
517 @end deftypefun
519 When a program terminates normally by returning from its @code{main}
520 function or by calling @code{exit}, the following actions occur in
521 sequence:
523 @enumerate
524 @item 
525 Functions that were registered with the @code{atexit} or @code{on_exit}
526 functions are called in the reverse order of their registration.  This
527 mechanism allows your application to specify its own ``cleanup'' actions
528 to be performed at program termination.  Typically, this is used to do
529 things like saving program state information in a file, or unlock locks
530 in shared data bases.
532 @item 
533 All open streams are closed; writing out any buffered output data.  See
534 @ref{Opening and Closing Streams}.  In addition, temporary files opened
535 with the @code{tmpfile} function are removed; see @ref{Temporary Files}.
537 @item 
538 @code{_exit} is called.  @xref{Termination Internals}
539 @end enumerate
541 @node Exit Status, Cleanups on Exit, Normal Program Termination, Program Termination
542 @subsection Exit Status
543 @cindex exit status
545 When a program exits, it can return to the parent process a small
546 amount of information about the cause of termination, using the
547 @dfn{exit status}.  This is a value between 0 and 255 that the exiting
548 process passes as an argument to @code{exit}.
550 Normally you should use the exit status to report very broad information
551 about success or failure.  You can't provide a lot of detail about the
552 reasons for the failure, and most parent processes would not want much
553 detail anyway.
555 There are conventions for what sorts of status values certain programs
556 should return.  The most common convention is simply 0 for success and 1
557 for failure.  Programs that perform comparison use a different
558 convention: they use status 1 to indicate a mismatch, and status 2 to
559 indicate an inability to compare.  Your program should follow an
560 existing convention if an existing convention makes sense for it.
562 A general convention reserves status values 128 and up for special
563 purposes.  In particular, the value 128 is used to indicate failure to
564 execute another program in a subprocess.  This convention is not
565 universally obeyed, but it is a good idea to follow it in your programs.
567 @strong{Warning:} Don't try to use the number of errors as the exit
568 status.  This is actually not very useful; a parent process would
569 generally not care how many errors occurred.  Worse than that, it does
570 not work, because the status value is truncated to eight bits.
571 Thus, if the program tried to report 256 errors, the parent would
572 receive a report of 0 errors---that is, success.
574 For the same reason, it does not work to use the value of @code{errno}
575 as the exit status---these can exceed 255.
577 @strong{Portability note:} Some non-POSIX systems use different
578 conventions for exit status values.  For greater portability, you can
579 use the macros @code{EXIT_SUCCESS} and @code{EXIT_FAILURE} for the
580 conventional status value for success and failure, respectively.  They
581 are declared in the file @file{stdlib.h}.
582 @pindex stdlib.h
584 @comment stdlib.h
585 @comment ANSI
586 @deftypevr Macro int EXIT_SUCCESS
587 This macro can be used with the @code{exit} function to indicate
588 successful program completion.
590 On POSIX systems, the value of this macro is @code{0}.  On other
591 systems, the value might be some other (possibly non-constant) integer
592 expression.
593 @end deftypevr
595 @comment stdlib.h
596 @comment ANSI
597 @deftypevr Macro int EXIT_FAILURE
598 This macro can be used with the @code{exit} function to indicate
599 unsuccessful program completion in a general sense.
601 On POSIX systems, the value of this macro is @code{1}.  On other
602 systems, the value might be some other (possibly non-constant) integer
603 expression.  Other nonzero status values also indicate future.  Certain
604 programs use different nonzero status values to indicate particular
605 kinds of "non-success".  For example, @code{diff} uses status value
606 @code{1} to mean that the files are different, and @code{2} or more to
607 mean that there was difficulty in opening the files.
608 @end deftypevr
610 @node Cleanups on Exit, Aborting a Program, Exit Status, Program Termination
611 @subsection Cleanups on Exit
613 @comment stdlib.h
614 @comment ANSI
615 @deftypefun int atexit (void (*@var{function}))
616 The @code{atexit} function registers the function @var{function} to be
617 called at normal program termination.  The @var{function} is called with
618 no arguments.
620 The return value from @code{atexit} is zero on success and nonzero if
621 the function cannot be registered. 
622 @end deftypefun
624 @comment stdlib.h
625 @comment GNU
626 @deftypefun int on_exit (void (*@var{function})(int @var{status}, void *@var{arg}), void *@var{arg})
627 This function is a somewhat more powerful variant of @code{atexit}.  It
628 accepts two arguments, a function @var{function} and an arbitrary
629 pointer @var{arg}.  At normal program termination, the @var{function} is
630 called with two arguments:  the @var{status} value passed to @code{exit},
631 and the @var{arg}.
633 This function is a GNU extension, and may not be supported by other
634 implementations.
635 @end deftypefun
637 Here's a trivial program that illustrates the use of @code{exit} and
638 @code{atexit}:
640 @example
641 #include <stdio.h>
642 #include <stdlib.h>
644 void bye (void)
646   printf ("Goodbye, cruel world....\n");
649 void main (void)
651   atexit (bye);
652   exit (EXIT_SUCCESS);
654 @end example
656 @noindent
657 When this program is executed, it just prints the message and exits.
660 @node Aborting a Program, Termination Internals, Cleanups on Exit, Program Termination
661 @subsection Aborting a Program
662 @cindex aborting a program
664 You can abort your program using the @code{abort} function.  The prototype
665 for this function is in @file{stdlib.h}.
666 @pindex stdlib.h
668 @comment stdlib.h
669 @comment ANSI
670 @deftypefun void abort ()
671 The @code{abort} function causes abnormal program termination, without
672 executing functions registered with @code{atexit} or @code{on_exit}.
674 This function actually terminates the process by raising a
675 @code{SIGABRT} signal, and your program can include a handler to
676 intercept this signal; see @ref{Signal Handling}.
678 @strong{Incomplete:}  Why would you want to define such a handler?
679 @end deftypefun
681 @node Termination Internals,  , Aborting a Program, Program Termination
682 @subsection Termination Internals
684 The @code{_exit} function is the primitive used for process termination
685 by @code{exit}.  It is declared in the header file @file{unistd.h}.
686 @pindex unistd.h
688 @comment unistd.h
689 @comment POSIX.1
690 @deftypefun void _exit (int @var{status})
691 The @code{_exit} function is the primitive for causing a process to
692 terminate with status @var{status}.  Calling this function does not
693 execute cleanup functions registered with @code{atexit} or
694 @code{on_exit}.
695 @end deftypefun
697 When a process terminates for any reason---either by an explicit
698 termination call, or termination as a result of a signal---the
699 following things happen:
701 @itemize @bullet
702 @item
703 All open file descriptors in the process are closed.  @xref{Low-Level
704 Input/Output}.
706 @item
707 The low-order 8 bits of the return status code are saved to be reported
708 back to the parent process via @code{wait} or @code{waitpid}; see
709 @ref{Process Completion}.
711 @item
712 Any child processes of the process being terminated are assigned a new
713 parent process.  (This is the @code{init} process, with process ID 1.)
715 @item
716 A @code{SIGCHLD} signal is sent to the parent process.
718 @item
719 If the process is a session leader that has a controlling terminal, then
720 a @code{SIGHUP} signal is sent to each process in the foreground job,
721 and the controlling terminal is disassociated from that session.
722 @xref{Job Control}.
724 @item
725 If termination of a process causes a process group to become orphaned,
726 and any member of that process group is stopped, then a @code{SIGHUP}
727 signal and a @code{SIGCONT} signal are sent to each process in the
728 group.  @xref{Job Control}.
729 @end itemize
731 @node Creating New Processes,  , Program Termination, Processes
732 @section Creating New Processes
734 This section describes how your program can cause other programs to be
735 executed.  Actually, there are three distinct operations involved:
736 creating a new child process, causing the new process to execute a
737 program, and coordinating the completion of the child process with the
738 original program.
740 The @code{system} function provides a simple, portable mechanism for
741 running another program; it does all three steps automatically.  If you
742 need more control over the details of how this is done, you can use the
743 primitive functions to do each step individually instead.
745 @menu
746 * Running a Command::           The easy way to run another program.
747 * Process Creation Concepts::   An overview of the hard way to do it.
748 * Process Identification::      How to get the process ID of a process.
749 * Creating a Process::          How to fork a child process.
750 * Executing a File::            How to get a process to execute another
751                                          program.
752 * Process Completion::          How to tell when a child process has
753                                          completed.
754 * Process Completion Status::   How to interpret the status value 
755                                          returned from a child process.
756 * BSD wait Functions::  More functions, for backward
757                                          compatibility.
758 * Process Creation Example::    A complete example program.
759 @end menu
762 @node Running a Command, Process Creation Concepts,  , Creating New Processes
763 @subsection Running a Command
764 @cindex running a command
766 The easy way to run another program is to use the @code{system}
767 function.  This function does all the work of running a subprogram, but
768 it doesn't give you much control over the details: you have to wait
769 until the subprogram terminates before you can do anything else.
771 @pindex stdlib.h
773 @comment stdlib.h
774 @comment ANSI
775 @deftypefun int system (const char *@var{command})
776 This function executes @var{command} as a shell command.  In the GNU C
777 library, it always uses the default shell @code{sh} to run the command.
778 In particular, it searching the directories in @code{PATH} to find
779 programs to execute.  The return value is @code{-1} if it wasn't
780 possible to create the shell process, and otherwise is the status of the
781 shell process.  @xref{Process Completion}, for details on how this
782 status code can be interpreted.
783 @pindex sh
784 @end deftypefun
786 The @code{system} function is declared in the header file
787 @file{stdlib.h}.
789 @strong{Portability Note:} Some C implementations may not have any
790 notion of a command processor that can execute other programs.  You can
791 determine whether a command processor exists by executing @code{system
792 (o)}; in this case the return value is nonzero if and only if such a
793 processor is available.
795 The @code{popen} and @code{pclose} functions (@pxref{Pipe to a
796 Subprocess}) are closely related to the @code{system} function.  They
797 allow the parent process to communicate with the standard input and
798 output channels of the command being executed.
800 @node Process Creation Concepts, Process Identification, Running a Command, Creating New Processes
801 @subsection Process Creation Concepts
803 This section gives an overview of processes and of the steps involved in
804 creating a process and making it run another program.
806 @cindex process ID
807 @cindex process lifetime
808 Each process is named by a @dfn{process ID} number.  A unique process ID
809 is allocated to each process when it is created.  The @dfn{lifetime} of
810 a process ends when its termination is reported to its parent process;
811 at that time, all of the process resources, including its process ID,
812 are freed.
814 @cindex creating a process
815 @cindex forking a process
816 @cindex child process
817 @cindex parent process
818 Processes are created with the @code{fork} system call (so the operation
819 of creating a new process is sometimes called @dfn{forking} a process).
820 The @dfn{child process} created by @code{fork} is an exact clone of the
821 original @dfn{parent process}, except that it has its own process ID.
823 After forking a child process, both the parent and child processes
824 continue to execute normally.  If you want your program to wait for a
825 child process to finish executing before continuing, you must do this
826 explicitly after the fork operation.  This is done with the @code{wait}
827 or @code{waitpid} functions (@pxref{Process Completion}).  These
828 functions give the parent information about why the child
829 terminated---for example, its exit status code.
831 A newly forked child process continues to execute the same program as
832 its parent process, at the point where the @code{fork} call returns.
833 You can use the return value from @code{fork} to tell whether the program
834 is running in the parent process or the child.
836 @cindex process image
837 Having all processes run the same program is usually not very useful.
838 But the child can execute another program using one of the @code{exec}
839 functions; see @ref{Executing a File}.  The program that the process is
840 executing is called its @dfn{process image}.  Starting execution of a
841 new program causes the process to forget all about its current process
842 image; when the new program exits, the process exits too, instead of
843 returning to the previous process image.
846 @node Process Identification, Creating a Process, Process Creation Concepts, Creating New Processes
847 @subsection Process Identification
849 The @code{pid_t} data type represents process IDs.  You can get the
850 process ID of a process by calling @code{getpid}.  The function
851 @code{getppid} returns the process ID of the parent of the parent of the
852 current process (this is also known as the @dfn{parent process ID}).
853 Your program should include the header files @file{unistd.h} and
854 @file{sys/types.h} to use these functions.
855 @pindex sys/types.h
856 @pindex unistd.h
858 @comment sys/types.h
859 @comment POSIX.1
860 @deftp {Data Type} pid_t
861 The @code{pid_t} data type is a signed integer type which is capable
862 of representing a process ID.  In the GNU library, this is an @code{int}.
863 @end deftp
865 @comment unistd.h
866 @comment POSIX.1
867 @deftypefun pid_t getpid ()
868 The @code{getpid} function returns the process ID of the current process.
869 @end deftypefun
871 @comment unistd.h
872 @comment POSIX.1
873 @deftypefun pid_t getppid ()
874 The @code{getppid} function returns the process ID of the parent of the
875 current process.
876 @end deftypefun
878 @node Creating a Process, Executing a File, Process Identification, Creating New Processes
879 @subsection Creating a Process
881 The @code{fork} function is the primitive for creating a process.
882 It is declared in the header file @file{unistd.h}.
883 @pindex unistd.h
885 @comment unistd.h
886 @comment POSIX.1
887 @deftypefun pid_t fork ()
888 The @code{fork} function creates a new process.
890 If the operation is successful, there are then both parent and child
891 processes and both see @code{fork} return, but with different values: it
892 returns a value of @code{0} in the child process and returns the child's
893 process ID in the parent process.  If the child process could not be
894 created, a value of @code{-1} is returned in the parent process.  The
895 following @code{errno} error conditions are defined for this function:
897 @table @code
898 @item EAGAIN
899 There aren't enough system resources to create another process, or the
900 user already has too many processes running.
902 @item ENOMEM
903 The process requires more space than the system can supply.
904 @end table
905 @end deftypefun
907 The specific attributes of the child process that differ from the
908 parent process are:
910 @itemize @bullet
911 @item
912 The child process has its own unique process ID.
914 @item
915 The parent process ID of the child process is the process ID of its
916 parent process.
918 @item
919 The child process gets its own copies of the parent process's open file
920 descriptors.  Subsequently changing attributes of the file descriptors
921 in the parent process won't affect the file descriptors in the child,
922 and vice versa.  @xref{Control Operations}.
924 @item
925 The elapsed processor times for the child process are set to zero;
926 see @ref{Processor Time}.
928 @item
929 The child doesn't inherit file locks set by the parent process.
930 @xref{Control Operations}.
932 @item
933 The child doesn't inherit alarms set by the parent process.
934 @xref{Setting an Alarm}.
936 @item
937 The set of pending signals (@pxref{Delivery of Signal}) for the child
938 process is cleared.  (The child process inherits its mask of blocked
939 signals and signal actions from the parent process.)
940 @end itemize 
943 @comment unistd.h
944 @comment BSD
945 @deftypefun pid_t vfork (void)
946 The @code{vfork} function is similar to @code{fork} but more efficient;
947 however, there are restrictions you must follow to use it safely.
949 While @code{fork} makes a complete copy of the calling process's address
950 space and allows both the parent and child to execute independently,
951 @code{vfork} does not make this copy.  Instead, the child process
952 created with @code{vfork} shares its parent's address space until it calls
953 one of the @code{exec} functions.  In the meantime, the parent process
954 suspends execution.
956 You must be very careful not to allow the child process created with
957 @code{vfork} to modify any global data or even local variables shared
958 with the parent.  Furthermore, the child process cannot return from (or
959 do a long jump out of) the function that called @code{vfork}!  This
960 would leave the parent process's control information very confused.  If
961 in doubt, use @code{fork} instead.
963 Some operating systems don't really implement @code{vfork}.  The GNU C
964 library permits you to use @code{vfork} on all systems, but actually
965 executes @code{fork} if @code{vfork} isn't available.
966 @end deftypefun
968 @node Executing a File, Process Completion, Creating a Process, Creating New Processes
969 @subsection Executing a File
970 @cindex executing a file
971 @cindex @code{exec} functions
973 This section describes the @code{exec} family of functions, for executing
974 a file as a process image.  You can use these functions to make a child
975 process execute a new program after it has been forked.
977 The functions in this family differ in how you specify the arguments,
978 but otherwise they all do the same thing.  They are declared in the
979 header file @file{unistd.h}.
980 @pindex unistd.h
982 @comment unistd.h
983 @comment POSIX.1
984 @deftypefun int execv (const char *@var{filename}, char *const @var{argv}@t{[]})
985 The @code{execv} function executes the file named by @var{filename} as a
986 new process image.
988 The @var{argv} argument is an array of null-terminated strings that is
989 used to provide a value for the @code{argv} argument to the @code{main}
990 function of the program to be executed.  The last element of this array
991 must be a null pointer.  @xref{Program Arguments}, for information on
992 how programs can access these arguments.
994 The environment for the new process image is taken from the
995 @code{environ} variable of the current process image; see @ref{Environment
996 Variables}, for information about environments.
997 @end deftypefun
999 @comment unistd.h
1000 @comment POSIX.1
1001 @deftypefun int execl (const char *@var{filename}, const char *@var{arg0}, @dots{})
1002 This is similar to @code{execv}, but the @var{argv} strings are
1003 specified individually instead of as an array.  A null pointer must be
1004 passed as the last such argument.
1005 @end deftypefun
1007 @comment unistd.h
1008 @comment POSIX.1
1009 @deftypefun int execve (const char *@var{filename}, char *const @var{argv}@t{[]}, char *const @var{env}@t{[]})
1010 This is similar to @code{execv}, but permits you to specify the environment
1011 for the new program explicitly as the @var{env} argument.  This should
1012 be an array of strings in the same format as for the @code{environ} 
1013 variable; see @ref{Environment Access}.
1014 @end deftypefun
1016 @comment unistd.h
1017 @comment POSIX.1
1018 @deftypefun int execle (const char *@var{filename}, const char *@var{arg0}, char *const @var{env}@t{[]}, @dots{})
1019 This is similar to @code{execl}, but permits you to specify the
1020 environment for the new program explicitly.  The environment argument is
1021 passed following the null pointer that marks the last @var{argv}
1022 argument, and should be an array of strings in the same format as for
1023 the @code{environ} variable.
1024 @end deftypefun
1026 @comment unistd.h
1027 @comment POSIX.1
1028 @deftypefun int execvp (const char *@var{filename}, char *const @var{argv}@t{[]})
1029 The @code{execvp} function is similar to @code{execv}, except that it
1030 searches the directories listed in the @code{PATH} environment variable
1031 (@pxref{Standard Environment Variables}) to find the full file name of a
1032 file from @var{filename} if @var{filename} does not contain a slash.
1034 This function is useful for executing installed system utility programs,
1035 so that the user can control where to look for them.  It is also useful
1036 in shells, for executing commands typed by the user.
1037 @end deftypefun
1039 @comment unistd.h
1040 @comment POSIX.1
1041 @deftypefun int execlp (const char *@var{filename}, const char *@var{arg0}, @dots{})
1042 This function is like @code{execl}, except that it performs the same
1043 file name searching as the @code{execvp} function.
1044 @end deftypefun
1047 The size of the argument list and environment list taken together must not
1048 be greater than @code{ARG_MAX} bytes.  @xref{System Parameters}.
1050 @strong{Incomplete:}  The POSIX.1 standard requires some statement here
1051 about how null terminators, null pointers, and alignment requirements
1052 affect the total size of the argument and environment lists.
1054 These functions normally don't return, since execution of a new program
1055 causes the currently executing program to go away completely.  A value
1056 of @code{-1} is returned in the event of a failure.  In addition to the
1057 usual file name syntax errors (@pxref{File Name Errors}), the following
1058 @code{errno} error conditions are defined for these functions:
1060 @table @code
1061 @item E2BIG
1062 The combined size of the new program's argument list and environment list
1063 is larger than @code{ARG_MAX} bytes.
1065 @item ENOEXEC
1066 The specified file can't be executed because it isn't in the right format.
1068 @item ENOMEM
1069 Executing the specified file requires more storage than is available.
1070 @end table
1072 If execution of the new file is successful, the access time field of the
1073 file is updated as if the file had been opened.  @xref{File Times}, for
1074 more details about access times of files.
1076 The point at which the file is closed again is not specified, but
1077 is at some point before the process exits or before another process
1078 image is executed.
1080 Executing a new process image completely changes the contents of memory,
1081 except for the arguments and the environment, but many other attributes
1082 of the process are unchanged:
1084 @itemize @bullet
1085 @item
1086 The process ID and the parent process ID.  @xref{Process Creation Concepts}.
1088 @item
1089 Session and process group membership.  @xref{Job Control Concepts}.
1091 @item
1092 Real user ID and group ID, and supplementary group IDs.  @xref{User/Group
1093 IDs of a Process}.
1095 @item
1096 Pending alarms.  @xref{Setting an Alarm}.
1098 @item
1099 Current working directory and root directory.  @xref{Working Directory}.
1101 @item
1102 File mode creation mask.  @xref{Setting Permissions}.
1104 @item
1105 Process signal mask; see @ref{Process Signal Mask}.
1107 @item
1108 Pending signals; see @ref{Blocking Signals}.
1110 @item
1111 Elapsed processor time associated with the process; see @ref{Processor Time}.
1112 @end itemize
1114 If the set-user-ID and set-group-ID mode bits of the process image file
1115 are set, this affects the effective user ID and effective group ID
1116 (respectively) of the process.  These concepts are discussed in detail
1117 in @ref{User/Group IDs of a Process}.
1119 Signals that are set to be ignored in the existing process image are
1120 also set to be ignored in the new process image.  All other signals are
1121 set to the default action in the new process image.  For more
1122 information about signals, see @ref{Signal Handling}.
1124 File descriptors open in the existing process image remain open in the
1125 new process image, unless they have the @code{FD_CLOEXEC}
1126 (close-on-exec) flag set.  The files that remain open inherit all
1127 attributes of the open file description from the existing process image,
1128 including file locks.  File descriptors are discussed in @ref{Low-Level
1129 Input/Output}.
1131 Streams, by contrast, cannot survive through @code{exec} functions,
1132 because they are located in the memory of the process itself.  The new
1133 process image has no streams except those it creates afresh.  Each of
1134 the streams in the pre-@code{exec} process image has a descriptor inside
1135 it, and these descriptors do survive through @code{exec} (provided that
1136 they do not have @code{FD_CLOEXEC} set.  The new process image can
1137 reconnect these to new streams using @code{fdopen}.
1139 @node Process Completion, Process Completion Status, Executing a File, Creating New Processes
1140 @subsection Process Completion
1141 @cindex process completion
1142 @cindex waiting for completion of child process
1143 @cindex testing exit status of child process
1145 The functions described in this section are used to wait for a child
1146 process to terminate or stop, and determine its status.  These functions
1147 are declared in the header file @file{sys/wait.h}.
1148 @pindex sys/wait.h
1150 @comment sys/wait.h
1151 @comment POSIX.1
1152 @deftypefun pid_t waitpid (pid_t @var{pid}, int *@var{status_ptr}, int @var{options})
1153 The @code{waitpid} function is used to request status information from a
1154 child process whose process ID is @var{pid}.  Normally, the calling
1155 process is suspended until the child process makes status information
1156 available by terminating.
1158 Other values for the @var{pid} argument have special interpretations.  A
1159 value of @code{-1} or @code{WAIT_ANY} requests status information for
1160 any child process; a value of @code{0} or @code{WAIT_MYPGRP} requests
1161 information for any child process in the same process group as the
1162 calling process; and any other negative value @minus{} @var{pgid}
1163 requests information for any child process whose process group ID is
1164 @var{pgid}.
1166 If status information for a child process is available immediately, this
1167 function returns immediately without waiting.  If more than one eligible
1168 child process has status information available, one of them is chosen
1169 randomly, and its status is returned immediately.  To get the status
1170 from the other programs, you need to call @code{waitpid} again.
1172 The @var{options} argument is a bit mask.  Its value should be the
1173 bitwise OR (that is, the @samp{|} operator) of zero or more of the
1174 @code{WNOHANG} and @code{WUNTRACED} flags.  You can use the
1175 @code{WNOHANG} flag to indicate that the parent process shouldn't wait;
1176 and the @code{WUNTRACED} flag to request status information from stopped
1177 processes as well as processes that have terminated.
1179 The status information from the child process is stored in the object
1180 that @var{status_ptr} points to, unless @var{status_ptr} is a null pointer.
1182 The return value is normally the process ID of the child process whose
1183 status is reported.  If the @code{WNOHANG} option was specified and no
1184 child process is waiting to be noticed, a value of zero is returned.  A
1185 value of @code{-1} is returned in case of error.  The following
1186 @code{errno} error conditions are defined for this function:
1188 @table @code
1189 @item EINTR
1190 The function was interrupted by delivery of a signal to the calling
1191 process.
1193 @item ECHILD
1194 There are no child processes to wait for, or the specified @var{pid}
1195 is not a child of the calling process.
1197 @item EINVAL
1198 An invalid value was provided for the @var{options} argument.
1199 @end table
1200 @end deftypefun
1202 These symbolic constants are defined as values for the @var{pid} argument
1203 to the @code{waitpid} function.
1205 @table @code
1206 @item WAIT_ANY
1207 This constant macro (whose value is @code{-1}) specifies that
1208 @code{waitpid} should return status information about any child process.
1210 @item WAIT_MYPGRP
1211 This constant (with value @code{0}) specifies that @code{waitpid} should
1212 return status information about any child process in the same process
1213 group as the calling process.
1215 These symbolic constants are defined as flags for the @var{options}
1216 argument to the @code{waitpid} function.  You can bitwise-OR the flags
1217 together to obtain a value to use as the argument.
1219 @item WNOHANG
1220 This flag specifies that @code{waitpid} should return immediately
1221 instead of waiting if there is no child process ready to be noticed.
1223 @item WUNTRACED
1224 This macro is used to specify that @code{waitpid} should also report the
1225 status of any child processes that have been stopped as well as those
1226 that have terminated.
1227 @end table
1229 @deftypefun pid_t wait (int *@var{status_ptr})
1230 This is a simplified version of @code{waitpid}, and is used to wait
1231 until any one child process terminates.
1233 @example
1234 wait (&status)
1235 @end example
1237 @noindent
1238 is equivalent to:
1240 @example
1241 waitpid (-1, &status, 0)
1242 @end example
1244 Here's an example of how to use @code{waitpid} to get the status from
1245 all child processes that have terminated, without ever waiting.  This
1246 function is designed to be used as a handler for @code{SIGCHLD}, the
1247 signal that indicates that at least one child process has terminated.
1249 @example
1250 void
1251 sigchld_handler (int signum)
1253   int pid;
1254   int status;
1255   while (1) @{
1256     pid = waitpid (WAIT_ANY, Estatus, WNOHANG);
1257     if (pid < 0) @{
1258       perror ("waitpid");
1259       break;
1260     @}
1261     if (pid == 0)
1262       break;
1263     notice_termination (pid, status);
1264   @}
1266 @end example
1267 @end deftypefun
1269 @node Process Completion Status, BSD wait Functions, Process Completion, Creating New Processes
1270 @subsection Process Completion Status
1272 If the exit status value (@pxref{Program Termination}) of the child
1273 process is zero, then the status value reported by @code{waitpid} or
1274 @code{wait} is also zero.  You can test for other kinds of information
1275 encoded in the returned status value using the following macros.
1276 These macros are defined in the header file @file{sys/wait.h}.
1277 @pindex sys/wait.h
1279 @comment sys/wait.h
1280 @comment POSIX.1
1281 @deftypefn Macro int WIFEXITED (int @var{status})
1282 This macro returns a non-zero value if the child process terminated
1283 normally with @code{exit} or @code{_exit}.
1284 @end deftypefn
1286 @comment sys/wait.h
1287 @comment POSIX.1
1288 @deftypefn Macro int WEXITSTATUS (int @var{status})
1289 If @code{WIFEXITED} is true of @var{status}, this macro returns the
1290 low-order 8 bits of the exit status value from the child process.
1291 @end deftypefn
1293 @comment sys/wait.h
1294 @comment POSIX.1
1295 @deftypefn Macro int WIFSIGNALED (int @var{status})
1296 This macro returns a non-zero value if the child process terminated
1297 by receiving a signal that was not handled.
1298 @end deftypefn
1300 @comment sys/wait.h
1301 @comment POSIX.1
1302 @deftypefn Macro int WTERMSIG (int @var{status})
1303 If @code{WIFSIGNALED} is true of @var{status}, this macro returns the
1304 number of the signal that terminated the child process.
1305 @end deftypefn
1307 @comment sys/wait.h
1308 @comment BSD
1309 @deftypefn Macro int WCOREDUMP (int @var{status})
1310 This macro returns a non-zero value if the child process terminated
1311 and produced a core dump.
1312 @end deftypefn
1314 @comment sys/wait.h
1315 @comment POSIX.1
1316 @deftypefn Macro int WIFSTOPPED (int @var{status})
1317 This macro returns a non-zero value if the child process is stopped.
1318 @end deftypefn
1320 @comment sys/wait.h
1321 @comment POSIX.1
1322 @deftypefn Macro int WSTOPSIG (int @var{status})
1323 If @code{WIFSTOPPED} is true of @var{status}, this macro returns the
1324 number of the signal that caused the child process to stop.
1325 @end deftypefn
1328 @node BSD wait Functions, Process Creation Example, Process Completion Status, Creating New Processes
1329 @subsection BSD Process Completion Functions
1331 The GNU library also provides these related facilities for compatibility
1332 with BSD Unix.  BSD uses the @code{union wait} data type to represent
1333 status values rather than an @code{int}.  The two representations are
1334 actually interchangeable; they describe the same bit patterns. The macros
1335 such as @code{WEXITSTATUS} are defined so that they will work on either
1336 kind of object, and the @code{wait} function is defined to accept either
1337 type of pointer as its @var{status_ptr} argument.
1339 These functions are declared in @file{sys/wait.h}.
1340 @pindex sys/wait.h
1342 @comment sys/wait.h
1343 @comment BSD
1344 @deftp {union Type} wait
1345 This data type represents program termination status values.  It has
1346 the following members:
1348 @table @code
1349 @item int w_termsig
1350 This member is equivalent to the @code{WTERMSIG} macro.
1352 @item int w_coredump
1353 This member is equivalent to the @code{WCOREDUMP} macro.
1355 @item int w_retcode
1356 This member is equivalent to the @code{WEXISTATUS} macro.
1358 @item int w_stopsig
1359 This member is equivalent to the @code{WSTOPSIG} macro.
1360 @end table
1362 Instead of accessing these members directly, you should use the
1363 equivalent macros.
1364 @end deftp
1366 @comment sys/wait.h
1367 @comment BSD
1368 @deftypefun pid_t wait3 (union wait *@var{status_ptr}, int @var{options}, void * @var{usage})
1369 If @var{usage} is a null pointer, this function is equivalent to
1370 @code{waitpid (-1, @var{status_ptr}, @var{options})}.
1372 The @var{usage} argument may also be a pointer to a 
1373 @code{struct rusage} object.  Information about system resources used by
1374 terminated processes (but not stopped processes) is returned in this
1375 structure.
1377 @strong{Incomplete:}  The description of the @code{struct rusage} structure
1378 hasn't been written yet.  Put in a cross-reference here.
1379 @end deftypefun
1381 @comment sys/wait.h
1382 @comment BSD
1383 @deftypefun pid_t wait4 (pid_t @var{pid}, union wait *@var{status_ptr}, int @var{options}, void *@var{usage})
1384 If @var{usage} is a null pointer, this function is equivalent to
1385 @code{waitpid (@var{pid}, @var{status_ptr}, @var{options})}.
1387 The @var{usage} argument may also be a pointer to a 
1388 @code{struct rusage} object.  Information about system resources used by
1389 terminated processes (but not stopped processes) is returned in this
1390 structure.
1392 @strong{Incomplete:}  The description of the @code{struct rusage} structure
1393 hasn't been written yet.  Put in a cross-reference here.
1394 @end deftypefun
1396 @node Process Creation Example,  , BSD wait Functions, Creating New Processes
1397 @subsection Process Creation Example
1399 Here is an example program showing how you might write a function
1400 similar to the built-in @code{system}.  It executes its @var{command}
1401 argument using the equivalent of @samp{sh -c @var{command}}.
1403 @example
1404 #include <stddef.h>
1405 #include <stdlib.h>
1406 #include <unistd.h>
1407 #include <sys/types.h>
1408 #include <sys/wait.h>
1410 /* @r{Execute the command using this shell program.}  */
1411 #define SHELL "/bin/sh"
1413 int 
1414 my_system (char *command)
1416   int status;
1417   pid_t pid;
1419   pid =  fork ();
1420   if (pid == 0) @{
1421     /* @r{This is the child process.  Execute the shell command.} */
1422     execl (SHELL, SHELL, "-c", command, NULL);
1423     exit (EXIT_FAILURE);
1424   @}
1425   else if (pid < 0)
1426     /* @r{The fork failed.  Report failure.}  */
1427     status = -1;
1428   else @{
1429     /* @r{This is the parent process.  Wait for the child to complete.}  */
1430     if (waitpid (pid, &status, 0) != pid)
1431       status = -1;
1432   @}
1433   return status;
1435 @end example
1437 @comment Yes, this example has been tested.
1439 There are a couple of things you should pay attention to in this
1440 example.
1442 Remember that the first @code{argv} argument supplied to the program
1443 represents the name of the program being executed.  That is why, in the
1444 call to @code{execl}, @code{SHELL} is supplied once to name the program
1445 to execute and a second time to supply a value for @code{argv[0]}.  
1447 The @code{execl} call in the child process doesn't return if it is
1448 successful.  If it fails, you must do something to make the child
1449 process terminate.  Just returning a bad status code with @code{return}
1450 would leave two processes running the original program.  Instead, the
1451 right behavior is for the child process to report failure to its parent
1452 process.  To do this, @code{exit} is called with a failure status.