]> git.ipfire.org Git - thirdparty/glibc.git/blob - manual/startup.texi
initial import
[thirdparty/glibc.git] / manual / startup.texi
1 @node Process Startup
2 @chapter Process Startup and Termination
3
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.
11
12 This chapter explains what your program should do to handle the startup
13 of a process, to terminate its process, and to receive information
14 (arguments and the environment) from the parent process.
15
16 @menu
17 * Program Arguments:: Parsing your program's command-line arguments.
18 * Environment Variables:: How to access parameters inherited from
19 a parent process.
20 * Program Termination:: How to cause a process to terminate and
21 return status information to its parent.
22 @end menu
23
24 @node Program Arguments
25 @section Program Arguments
26 @cindex program arguments
27 @cindex command line arguments
28 @cindex arguments, to program
29
30 @cindex program startup
31 @cindex startup of program
32 @cindex invocation of program
33 @cindex @code{main} function
34 @findex main
35 The system starts a C program by calling the function @code{main}. It
36 is up to you to write a function named @code{main}---otherwise, you
37 won't even be able to link your program without errors.
38
39 In ANSI C you can define @code{main} either to take no arguments, or to
40 take two arguments that represent the command line arguments to the
41 program, like this:
42
43 @smallexample
44 int main (int @var{argc}, char *@var{argv}[])
45 @end smallexample
46
47 @cindex argc (program argument count)
48 @cindex argv (program argument vector)
49 The command line arguments are the whitespace-separated tokens given in
50 the shell command used to invoke the program; thus, in @samp{cat foo
51 bar}, the arguments are @samp{foo} and @samp{bar}. The only way a
52 program can look at its command line arguments is via the arguments of
53 @code{main}. If @code{main} doesn't take arguments, then you cannot get
54 at the command line.
55
56 The value of the @var{argc} argument is the number of command line
57 arguments. The @var{argv} argument is a vector of C strings; its
58 elements are the individual command line argument strings. The file
59 name of the program being run is also included in the vector as the
60 first element; the value of @var{argc} counts this element. A null
61 pointer always follows the last element: @code{@var{argv}[@var{argc}]}
62 is this null pointer.
63
64 For the command @samp{cat foo bar}, @var{argc} is 3 and @var{argv} has
65 three elements, @code{"cat"}, @code{"foo"} and @code{"bar"}.
66
67 If the syntax for the command line arguments to your program is simple
68 enough, you can simply pick the arguments off from @var{argv} by hand.
69 But unless your program takes a fixed number of arguments, or all of the
70 arguments are interpreted in the same way (as file names, for example),
71 you are usually better off using @code{getopt} to do the parsing.
72
73 In Unix systems you can define @code{main} a third way, using three arguments:
74
75 @smallexample
76 int main (int @var{argc}, char *@var{argv}[], char *@var{envp})
77 @end smallexample
78
79 The first two arguments are just the same. The third argument
80 @var{envp} gives the process's environment; it is the same as the value
81 of @code{environ}. @xref{Environment Variables}. POSIX.1 does not
82 allow this three-argument form, so to be portable it is best to write
83 @code{main} to take two arguments, and use the value of @code{environ}.
84
85 @menu
86 * Argument Syntax:: By convention, options start with a hyphen.
87 * Parsing Options:: The @code{getopt} function.
88 * Example of Getopt:: An example of parsing options with @code{getopt}.
89 * Long Options:: GNU suggests utilities accept long-named options.
90 Here is how to do that.
91 * Long Option Example:: An example of using @code{getopt_long}.
92 @end menu
93
94 @node Argument Syntax
95 @subsection Program Argument Syntax Conventions
96 @cindex program argument syntax
97 @cindex syntax, for program arguments
98 @cindex command argument syntax
99
100 POSIX recommends these conventions for command line arguments.
101 @code{getopt} (@pxref{Parsing Options}) makes it easy to implement them.
102
103 @itemize @bullet
104 @item
105 Arguments are options if they begin with a hyphen delimiter (@samp{-}).
106
107 @item
108 Multiple options may follow a hyphen delimiter in a single token if
109 the options do not take arguments. Thus, @samp{-abc} is equivalent to
110 @samp{-a -b -c}.
111
112 @item
113 Option names are single alphanumeric characters (as for @code{isalnum};
114 see @ref{Classification of Characters}).
115
116 @item
117 Certain options require an argument. For example, the @samp{-o} command
118 of the @code{ld} command requires an argument---an output file name.
119
120 @item
121 An option and its argument may or may not appear as separate tokens. (In
122 other words, the whitespace separating them is optional.) Thus,
123 @w{@samp{-o foo}} and @samp{-ofoo} are equivalent.
124
125 @item
126 Options typically precede other non-option arguments.
127
128 The implementation of @code{getopt} in the GNU C library normally makes
129 it appear as if all the option arguments were specified before all the
130 non-option arguments for the purposes of parsing, even if the user of
131 your program intermixed option and non-option arguments. It does this
132 by reordering the elements of the @var{argv} array. This behavior is
133 nonstandard; if you want to suppress it, define the
134 @code{_POSIX_OPTION_ORDER} environment variable. @xref{Standard
135 Environment}.
136
137 @item
138 The argument @samp{--} terminates all options; any following arguments
139 are treated as non-option arguments, even if they begin with a hyphen.
140
141 @item
142 A token consisting of a single hyphen character is interpreted as an
143 ordinary non-option argument. By convention, it is used to specify
144 input from or output to the standard input and output streams.
145
146 @item
147 Options may be supplied in any order, or appear multiple times. The
148 interpretation is left up to the particular application program.
149 @end itemize
150
151 @cindex long-named options
152 GNU adds @dfn{long options} to these conventions. Long options consist
153 of @samp{--} followed by a name made of alphanumeric characters and
154 dashes. Option names are typically one to three words long, with
155 hyphens to separate words. Users can abbreviate the option names as
156 long as the abbreviations are unique.
157
158 To specify an argument for a long option, write
159 @samp{--@var{name}=@var{value}}. This syntax enables a long option to
160 accept an argument that is itself optional.
161
162 Eventually, the GNU system will provide completion for long option names
163 in the shell.
164
165 @node Parsing Options
166 @subsection Parsing Program Options
167 @cindex program arguments, parsing
168 @cindex command arguments, parsing
169 @cindex parsing program arguments
170
171 Here are the details about how to call the @code{getopt} function. To
172 use this facility, your program must include the header file
173 @file{unistd.h}.
174 @pindex unistd.h
175
176 @comment unistd.h
177 @comment POSIX.2
178 @deftypevar int opterr
179 If the value of this variable is nonzero, then @code{getopt} prints an
180 error message to the standard error stream if it encounters an unknown
181 option character or an option with a missing required argument. This is
182 the default behavior. If you set this variable to zero, @code{getopt}
183 does not print any messages, but it still returns the character @code{?}
184 to indicate an error.
185 @end deftypevar
186
187 @comment unistd.h
188 @comment POSIX.2
189 @deftypevar int optopt
190 When @code{getopt} encounters an unknown option character or an option
191 with a missing required argument, it stores that option character in
192 this variable. You can use this for providing your own diagnostic
193 messages.
194 @end deftypevar
195
196 @comment unistd.h
197 @comment POSIX.2
198 @deftypevar int optind
199 This variable is set by @code{getopt} to the index of the next element
200 of the @var{argv} array to be processed. Once @code{getopt} has found
201 all of the option arguments, you can use this variable to determine
202 where the remaining non-option arguments begin. The initial value of
203 this variable is @code{1}.
204 @end deftypevar
205
206 @comment unistd.h
207 @comment POSIX.2
208 @deftypevar {char *} optarg
209 This variable is set by @code{getopt} to point at the value of the
210 option argument, for those options that accept arguments.
211 @end deftypevar
212
213 @comment unistd.h
214 @comment POSIX.2
215 @deftypefun int getopt (int @var{argc}, char **@var{argv}, const char *@var{options})
216 The @code{getopt} function gets the next option argument from the
217 argument list specified by the @var{argv} and @var{argc} arguments.
218 Normally these values come directly from the arguments received by
219 @code{main}.
220
221 The @var{options} argument is a string that specifies the option
222 characters that are valid for this program. An option character in this
223 string can be followed by a colon (@samp{:}) to indicate that it takes a
224 required argument.
225
226 If the @var{options} argument string begins with a hyphen (@samp{-}), this
227 is treated specially. It permits arguments that are not options to be
228 returned as if they were associated with option character @samp{\0}.
229
230 The @code{getopt} function returns the option character for the next
231 command line option. When no more option arguments are available, it
232 returns @code{-1}. There may still be more non-option arguments; you
233 must compare the external variable @code{optind} against the @var{argc}
234 parameter to check this.
235
236 If the option has an argument, @code{getopt} returns the argument by
237 storing it in the varables @var{optarg}. You don't ordinarily need to
238 copy the @code{optarg} string, since it is a pointer into the original
239 @var{argv} array, not into a static area that might be overwritten.
240
241 If @code{getopt} finds an option character in @var{argv} that was not
242 included in @var{options}, or a missing option argument, it returns
243 @samp{?} and sets the external variable @code{optopt} to the actual
244 option character. If the first character of @var{options} is a colon
245 (@samp{:}), then @code{getopt} returns @samp{:} instead of @samp{?} to
246 indicate a missing option argument. In addition, if the external
247 variable @code{opterr} is nonzero (which is the default), @code{getopt}
248 prints an error message.
249 @end deftypefun
250
251 @node Example of Getopt
252 @subsection Example of Parsing Arguments with @code{getopt}
253
254 Here is an example showing how @code{getopt} is typically used. The
255 key points to notice are:
256
257 @itemize @bullet
258 @item
259 Normally, @code{getopt} is called in a loop. When @code{getopt} returns
260 @code{-1}, indicating no more options are present, the loop terminates.
261
262 @item
263 A @code{switch} statement is used to dispatch on the return value from
264 @code{getopt}. In typical use, each case just sets a variable that
265 is used later in the program.
266
267 @item
268 A second loop is used to process the remaining non-option arguments.
269 @end itemize
270
271 @smallexample
272 @include testopt.c.texi
273 @end smallexample
274
275 Here are some examples showing what this program prints with different
276 combinations of arguments:
277
278 @smallexample
279 % testopt
280 aflag = 0, bflag = 0, cvalue = (null)
281
282 % testopt -a -b
283 aflag = 1, bflag = 1, cvalue = (null)
284
285 % testopt -ab
286 aflag = 1, bflag = 1, cvalue = (null)
287
288 % testopt -c foo
289 aflag = 0, bflag = 0, cvalue = foo
290
291 % testopt -cfoo
292 aflag = 0, bflag = 0, cvalue = foo
293
294 % testopt arg1
295 aflag = 0, bflag = 0, cvalue = (null)
296 Non-option argument arg1
297
298 % testopt -a arg1
299 aflag = 1, bflag = 0, cvalue = (null)
300 Non-option argument arg1
301
302 % testopt -c foo arg1
303 aflag = 0, bflag = 0, cvalue = foo
304 Non-option argument arg1
305
306 % testopt -a -- -b
307 aflag = 1, bflag = 0, cvalue = (null)
308 Non-option argument -b
309
310 % testopt -a -
311 aflag = 1, bflag = 0, cvalue = (null)
312 Non-option argument -
313 @end smallexample
314
315 @node Long Options
316 @subsection Parsing Long Options
317
318 To accept GNU-style long options as well as single-character options,
319 use @code{getopt_long} instead of @code{getopt}. You should make every
320 program accept long options if it uses any options, for this takes
321 little extra work and helps beginners remember how to use the program.
322
323 @comment getopt.h
324 @comment GNU
325 @deftp {Data Type} {struct option}
326 This structure describes a single long option name for the sake of
327 @code{getopt_long}. The argument @var{longopts} must be an array of
328 these structures, one for each long option. Terminate the array with an
329 element containing all zeros.
330
331 The @code{struct option} structure has these fields:
332
333 @table @code
334 @item const char *name
335 This field is the name of the option. It is a string.
336
337 @item int has_arg
338 This field says whether the option takes an argument. It is an integer,
339 and there are three legitimate values: @w{@code{no_argument}},
340 @code{required_argument} and @code{optional_argument}.
341
342 @item int *flag
343 @itemx int val
344 These fields control how to report or act on the option when it occurs.
345
346 If @code{flag} is a null pointer, then the @code{val} is a value which
347 identifies this option. Often these values are chosen to uniquely
348 identify particular long options.
349
350 If @code{flag} is not a null pointer, it should be the address of an
351 @code{int} variable which is the flag for this option. The value in
352 @code{val} is the value to store in the flag to indicate that the option
353 was seen.
354 @end table
355 @end deftp
356
357 @comment getopt.h
358 @comment GNU
359 @deftypefun int getopt_long (int @var{argc}, char **@var{argv}, const char *@var{shortopts}, struct option *@var{longopts}, int *@var{indexptr})
360 Decode options from the vector @var{argv} (whose length is @var{argc}).
361 The argument @var{shortopts} describes the short options to accept, just as
362 it does in @code{getopt}. The argument @var{longopts} describes the long
363 options to accept (see above).
364
365 When @code{getopt_long} encounters a short option, it does the same
366 thing that @code{getopt} would do: it returns the character code for the
367 option, and stores the options argument (if it has one) in @code{optarg}.
368
369 When @code{getopt_long} encounters a long option, it takes actions based
370 on the @code{flag} and @code{val} fields of the definition of that
371 option.
372
373 If @code{flag} is a null pointer, then @code{getopt_long} returns the
374 contents of @code{val} to indicate which option it found. You should
375 arrange distinct values in the @code{val} field for options with
376 different meanings, so you can decode these values after
377 @code{getopt_long} returns. If the long option is equivalent to a short
378 option, you can use the short option's character code in @code{val}.
379
380 If @code{flag} is not a null pointer, that means this option should just
381 set a flag in the program. The flag is a variable of type @code{int}
382 that you define. Put the address of the flag in the @code{flag} field.
383 Put in the @code{val} field the value you would like this option to
384 store in the flag. In this case, @code{getopt_long} returns @code{0}.
385
386 For any long option, @code{getopt_long} tells you the index in the array
387 @var{longopts} of the options definition, by storing it into
388 @code{*@var{indexptr}}. You can get the name of the option with
389 @code{@var{longopts}[*@var{indexptr}].name}. So you can distinguish among
390 long options either by the values in their @code{val} fields or by their
391 indices. You can also distinguish in this way among long options that
392 set flags.
393
394 When a long option has an argument, @code{getopt_long} puts the argument
395 value in the variable @code{optarg} before returning. When the option
396 has no argument, the value in @code{optarg} is a null pointer. This is
397 how you can tell whether an optional argument was supplied.
398
399 When @code{getopt_long} has no more options to handle, it returns
400 @code{-1}, and leaves in the variable @code{optind} the index in
401 @var{argv} of the next remaining argument.
402 @end deftypefun
403
404 @node Long Option Example
405 @subsection Example of Parsing Long Options
406
407 @smallexample
408 @include longopt.c.texi
409 @end smallexample
410
411 @node Environment Variables
412 @section Environment Variables
413
414 @cindex environment variable
415 When a program is executed, it receives information about the context in
416 which it was invoked in two ways. The first mechanism uses the
417 @var{argv} and @var{argc} arguments to its @code{main} function, and is
418 discussed in @ref{Program Arguments}. The second mechanism uses
419 @dfn{environment variables} and is discussed in this section.
420
421 The @var{argv} mechanism is typically used to pass command-line
422 arguments specific to the particular program being invoked. The
423 environment, on the other hand, keeps track of information that is
424 shared by many programs, changes infrequently, and that is less
425 frequently used.
426
427 The environment variables discussed in this section are the same
428 environment variables that you set using assignments and the
429 @code{export} command in the shell. Programs executed from the shell
430 inherit all of the environment variables from the shell.
431 @c !!! xref to right part of bash manual when it exists
432
433 @cindex environment
434 Standard environment variables are used for information about the user's
435 home directory, terminal type, current locale, and so on; you can define
436 additional variables for other purposes. The set of all environment
437 variables that have values is collectively known as the
438 @dfn{environment}.
439
440 Names of environment variables are case-sensitive and must not contain
441 the character @samp{=}. System-defined environment variables are
442 invariably uppercase.
443
444 The values of environment variables can be anything that can be
445 represented as a string. A value must not contain an embedded null
446 character, since this is assumed to terminate the string.
447
448
449 @menu
450 * Environment Access:: How to get and set the values of
451 environment variables.
452 * Standard Environment:: These environment variables have
453 standard interpretations.
454 @end menu
455
456 @node Environment Access
457 @subsection Environment Access
458 @cindex environment access
459 @cindex environment representation
460
461 The value of an environment variable can be accessed with the
462 @code{getenv} function. This is declared in the header file
463 @file{stdlib.h}.
464 @pindex stdlib.h
465
466 @comment stdlib.h
467 @comment ANSI
468 @deftypefun {char *} getenv (const char *@var{name})
469 This function returns a string that is the value of the environment
470 variable @var{name}. You must not modify this string. In some non-Unix
471 systems not using the GNU library, it might be overwritten by subsequent
472 calls to @code{getenv} (but not by any other library function). If the
473 environment variable @var{name} is not defined, the value is a null
474 pointer.
475 @end deftypefun
476
477
478 @comment stdlib.h
479 @comment SVID
480 @deftypefun int putenv (const char *@var{string})
481 The @code{putenv} function adds or removes definitions from the environment.
482 If the @var{string} is of the form @samp{@var{name}=@var{value}}, the
483 definition is added to the environment. Otherwise, the @var{string} is
484 interpreted as the name of an environment variable, and any definition
485 for this variable in the environment is removed.
486
487 The GNU library provides this function for compatibility with SVID; it
488 may not be available in other systems.
489 @end deftypefun
490
491 @c !!! BSD function setenv
492
493 You can deal directly with the underlying representation of environment
494 objects to add more variables to the environment (for example, to
495 communicate with another program you are about to execute; see
496 @ref{Executing a File}).
497
498 @comment unistd.h
499 @comment POSIX.1
500 @deftypevar {char **} environ
501 The environment is represented as an array of strings. Each string is
502 of the format @samp{@var{name}=@var{value}}. The order in which
503 strings appear in the environment is not significant, but the same
504 @var{name} must not appear more than once. The last element of the
505 array is a null pointer.
506
507 This variable is declared in the header file @file{unistd.h}.
508
509 If you just want to get the value of an environment variable, use
510 @code{getenv}.
511 @end deftypevar
512
513 Unix systems, and the GNU system, pass the initial value of
514 @code{environ} as the third argument to @code{main}.
515 @xref{Program Arguments}.
516
517 @node Standard Environment
518 @subsection Standard Environment Variables
519 @cindex standard environment variables
520
521 These environment variables have standard meanings. This doesn't mean
522 that they are always present in the environment; but if these variables
523 @emph{are} present, they have these meanings. You shouldn't try to use
524 these environment variable names for some other purpose.
525
526 @comment Extra blank lines make it look better.
527 @table @code
528 @item HOME
529 @cindex HOME environment variable
530 @cindex home directory
531
532 This is a string representing the user's @dfn{home directory}, or
533 initial default working directory.
534
535 The user can set @code{HOME} to any value.
536 If you need to make sure to obtain the proper home directory
537 for a particular user, you should not use @code{HOME}; instead,
538 look up the user's name in the user database (@pxref{User Database}).
539
540 For most purposes, it is better to use @code{HOME}, precisely because
541 this lets the user specify the value.
542
543 @c !!! also USER
544 @item LOGNAME
545 @cindex LOGNAME environment variable
546
547 This is the name that the user used to log in. Since the value in the
548 environment can be tweaked arbitrarily, this is not a reliable way to
549 identify the user who is running a process; a function like
550 @code{getlogin} (@pxref{Who Logged In}) is better for that purpose.
551
552 For most purposes, it is better to use @code{LOGNAME}, precisely because
553 this lets the user specify the value.
554
555 @item PATH
556 @cindex PATH environment variable
557
558 A @dfn{path} is a sequence of directory names which is used for
559 searching for a file. The variable @code{PATH} holds a path used
560 for searching for programs to be run.
561
562 The @code{execlp} and @code{execvp} functions (@pxref{Executing a File})
563 use this environment variable, as do many shells and other utilities
564 which are implemented in terms of those functions.
565
566 The syntax of a path is a sequence of directory names separated by
567 colons. An empty string instead of a directory name stands for the
568 current directory (@pxref{Working Directory}).
569
570 A typical value for this environment variable might be a string like:
571
572 @smallexample
573 :/bin:/etc:/usr/bin:/usr/new/X11:/usr/new:/usr/local/bin
574 @end smallexample
575
576 This means that if the user tries to execute a program named @code{foo},
577 the system will look for files named @file{foo}, @file{/bin/foo},
578 @file{/etc/foo}, and so on. The first of these files that exists is
579 the one that is executed.
580
581 @c !!! also TERMCAP
582 @item TERM
583 @cindex TERM environment variable
584
585 This specifies the kind of terminal that is receiving program output.
586 Some programs can make use of this information to take advantage of
587 special escape sequences or terminal modes supported by particular kinds
588 of terminals. Many programs which use the termcap library
589 (@pxref{Finding a Terminal Description,Find,,termcap,The Termcap Library
590 Manual}) use the @code{TERM} environment variable, for example.
591
592 @item TZ
593 @cindex TZ environment variable
594
595 This specifies the time zone. @xref{TZ Variable}, for information about
596 the format of this string and how it is used.
597
598 @item LANG
599 @cindex LANG environment variable
600
601 This specifies the default locale to use for attribute categories where
602 neither @code{LC_ALL} nor the specific environment variable for that
603 category is set. @xref{Locales}, for more information about
604 locales.
605
606 @ignore
607 @c I doubt this really exists
608 @item LC_ALL
609 @cindex LC_ALL environment variable
610
611 This is similar to the @code{LANG} environment variable. However, its
612 value takes precedence over any values provided for the individual
613 attribute category environment variables, or for the @code{LANG}
614 environment variable.
615 @end ignore
616
617 @item LC_COLLATE
618 @cindex LC_COLLATE environment variable
619
620 This specifies what locale to use for string sorting.
621
622 @item LC_CTYPE
623 @cindex LC_CTYPE environment variable
624
625 This specifies what locale to use for character sets and character
626 classification.
627
628 @item LC_MONETARY
629 @cindex LC_MONETARY environment variable
630
631 This specifies what locale to use for formatting monetary values.
632
633 @item LC_NUMERIC
634 @cindex LC_NUMERIC environment variable
635
636 This specifies what locale to use for formatting numbers.
637
638 @item LC_TIME
639 @cindex LC_TIME environment variable
640
641 This specifies what locale to use for formatting date/time values.
642
643 @item _POSIX_OPTION_ORDER
644 @cindex _POSIX_OPTION_ORDER environment variable.
645
646 If this environment variable is defined, it suppresses the usual
647 reordering of command line arguments by @code{getopt}. @xref{Argument Syntax}.
648
649 @c !!! GNU also has COREFILE, CORESERVER, EXECSERVERS
650 @end table
651
652 @node Program Termination
653 @section Program Termination
654 @cindex program termination
655 @cindex process termination
656
657 @cindex exit status value
658 The usual way for a program to terminate is simply for its @code{main}
659 function to return. The @dfn{exit status value} returned from the
660 @code{main} function is used to report information back to the process's
661 parent process or shell.
662
663 A program can also terminate normally by calling the @code{exit}
664 function.
665
666 In addition, programs can be terminated by signals; this is discussed in
667 more detail in @ref{Signal Handling}. The @code{abort} function causes
668 a signal that kills the program.
669
670 @menu
671 * Normal Termination:: If a program calls @code{exit}, a
672 process terminates normally.
673 * Exit Status:: The @code{exit status} provides information
674 about why the process terminated.
675 * Cleanups on Exit:: A process can run its own cleanup
676 functions upon normal termination.
677 * Aborting a Program:: The @code{abort} function causes
678 abnormal program termination.
679 * Termination Internals:: What happens when a process terminates.
680 @end menu
681
682 @node Normal Termination
683 @subsection Normal Termination
684
685 A process terminates normally when the program calls @code{exit}.
686 Returning from @code{main} is equivalent to calling @code{exit}, and
687 the value that @code{main} returns is used as the argument to @code{exit}.
688
689 @comment stdlib.h
690 @comment ANSI
691 @deftypefun void exit (int @var{status})
692 The @code{exit} function terminates the process with status
693 @var{status}. This function does not return.
694 @end deftypefun
695
696 Normal termination causes the following actions:
697
698 @enumerate
699 @item
700 Functions that were registered with the @code{atexit} or @code{on_exit}
701 functions are called in the reverse order of their registration. This
702 mechanism allows your application to specify its own ``cleanup'' actions
703 to be performed at program termination. Typically, this is used to do
704 things like saving program state information in a file, or unlocking
705 locks in shared data bases.
706
707 @item
708 All open streams are closed, writing out any buffered output data. See
709 @ref{Closing Streams}. In addition, temporary files opened
710 with the @code{tmpfile} function are removed; see @ref{Temporary Files}.
711
712 @item
713 @code{_exit} is called, terminating the program. @xref{Termination Internals}.
714 @end enumerate
715
716 @node Exit Status
717 @subsection Exit Status
718 @cindex exit status
719
720 When a program exits, it can return to the parent process a small
721 amount of information about the cause of termination, using the
722 @dfn{exit status}. This is a value between 0 and 255 that the exiting
723 process passes as an argument to @code{exit}.
724
725 Normally you should use the exit status to report very broad information
726 about success or failure. You can't provide a lot of detail about the
727 reasons for the failure, and most parent processes would not want much
728 detail anyway.
729
730 There are conventions for what sorts of status values certain programs
731 should return. The most common convention is simply 0 for success and 1
732 for failure. Programs that perform comparison use a different
733 convention: they use status 1 to indicate a mismatch, and status 2 to
734 indicate an inability to compare. Your program should follow an
735 existing convention if an existing convention makes sense for it.
736
737 A general convention reserves status values 128 and up for special
738 purposes. In particular, the value 128 is used to indicate failure to
739 execute another program in a subprocess. This convention is not
740 universally obeyed, but it is a good idea to follow it in your programs.
741
742 @strong{Warning:} Don't try to use the number of errors as the exit
743 status. This is actually not very useful; a parent process would
744 generally not care how many errors occurred. Worse than that, it does
745 not work, because the status value is truncated to eight bits.
746 Thus, if the program tried to report 256 errors, the parent would
747 receive a report of 0 errors---that is, success.
748
749 For the same reason, it does not work to use the value of @code{errno}
750 as the exit status---these can exceed 255.
751
752 @strong{Portability note:} Some non-POSIX systems use different
753 conventions for exit status values. For greater portability, you can
754 use the macros @code{EXIT_SUCCESS} and @code{EXIT_FAILURE} for the
755 conventional status value for success and failure, respectively. They
756 are declared in the file @file{stdlib.h}.
757 @pindex stdlib.h
758
759 @comment stdlib.h
760 @comment ANSI
761 @deftypevr Macro int EXIT_SUCCESS
762 This macro can be used with the @code{exit} function to indicate
763 successful program completion.
764
765 On POSIX systems, the value of this macro is @code{0}. On other
766 systems, the value might be some other (possibly non-constant) integer
767 expression.
768 @end deftypevr
769
770 @comment stdlib.h
771 @comment ANSI
772 @deftypevr Macro int EXIT_FAILURE
773 This macro can be used with the @code{exit} function to indicate
774 unsuccessful program completion in a general sense.
775
776 On POSIX systems, the value of this macro is @code{1}. On other
777 systems, the value might be some other (possibly non-constant) integer
778 expression. Other nonzero status values also indicate future. Certain
779 programs use different nonzero status values to indicate particular
780 kinds of "non-success". For example, @code{diff} uses status value
781 @code{1} to mean that the files are different, and @code{2} or more to
782 mean that there was difficulty in opening the files.
783 @end deftypevr
784
785 @node Cleanups on Exit
786 @subsection Cleanups on Exit
787
788 Your program can arrange to run its own cleanup functions if normal
789 termination happens. If you are writing a library for use in various
790 application programs, then it is unreliable to insist that all
791 applications call the library's cleanup functions explicitly before
792 exiting. It is much more robust to make the cleanup invisible to the
793 application, by setting up a cleanup function in the library itself
794 using @code{atexit} or @code{on_exit}.
795
796 @comment stdlib.h
797 @comment ANSI
798 @deftypefun int atexit (void (*@var{function}) (void))
799 The @code{atexit} function registers the function @var{function} to be
800 called at normal program termination. The @var{function} is called with
801 no arguments.
802
803 The return value from @code{atexit} is zero on success and nonzero if
804 the function cannot be registered.
805 @end deftypefun
806
807 @comment stdlib.h
808 @comment SunOS
809 @deftypefun int on_exit (void (*@var{function})(int @var{status}, void *@var{arg}), void *@var{arg})
810 This function is a somewhat more powerful variant of @code{atexit}. It
811 accepts two arguments, a function @var{function} and an arbitrary
812 pointer @var{arg}. At normal program termination, the @var{function} is
813 called with two arguments: the @var{status} value passed to @code{exit},
814 and the @var{arg}.
815
816 This function is included in the GNU C library only for compatibility
817 for SunOS, and may not be supported by other implementations.
818 @end deftypefun
819
820 Here's a trivial program that illustrates the use of @code{exit} and
821 @code{atexit}:
822
823 @smallexample
824 @include atexit.c.texi
825 @end smallexample
826
827 @noindent
828 When this program is executed, it just prints the message and exits.
829
830 @node Aborting a Program
831 @subsection Aborting a Program
832 @cindex aborting a program
833
834 You can abort your program using the @code{abort} function. The prototype
835 for this function is in @file{stdlib.h}.
836 @pindex stdlib.h
837
838 @comment stdlib.h
839 @comment ANSI
840 @deftypefun void abort (void)
841 The @code{abort} function causes abnormal program termination. This
842 does not execute cleanup functions registered with @code{atexit} or
843 @code{on_exit}.
844
845 This function actually terminates the process by raising a
846 @code{SIGABRT} signal, and your program can include a handler to
847 intercept this signal; see @ref{Signal Handling}.
848 @end deftypefun
849
850 @c Put in by rms. Don't remove.
851 @cartouche
852 @strong{Future Change Warning:} Proposed Federal censorship regulations
853 may prohibit us from giving you information about the possibility of
854 calling this function. We would be required to say that this is not an
855 acceptable way of terminating a program.
856 @end cartouche
857
858 @node Termination Internals
859 @subsection Termination Internals
860
861 The @code{_exit} function is the primitive used for process termination
862 by @code{exit}. It is declared in the header file @file{unistd.h}.
863 @pindex unistd.h
864
865 @comment unistd.h
866 @comment POSIX.1
867 @deftypefun void _exit (int @var{status})
868 The @code{_exit} function is the primitive for causing a process to
869 terminate with status @var{status}. Calling this function does not
870 execute cleanup functions registered with @code{atexit} or
871 @code{on_exit}.
872 @end deftypefun
873
874 When a process terminates for any reason---either by an explicit
875 termination call, or termination as a result of a signal---the
876 following things happen:
877
878 @itemize @bullet
879 @item
880 All open file descriptors in the process are closed. @xref{Low-Level I/O}.
881 Note that streams are not flushed automatically when the process
882 terminates; @xref{I/O on Streams}.
883
884 @item
885 The low-order 8 bits of the return status code are saved to be reported
886 back to the parent process via @code{wait} or @code{waitpid}; see
887 @ref{Process Completion}.
888
889 @item
890 Any child processes of the process being terminated are assigned a new
891 parent process. (On most systems, including GNU, this is the @code{init}
892 process, with process ID 1.)
893
894 @item
895 A @code{SIGCHLD} signal is sent to the parent process.
896
897 @item
898 If the process is a session leader that has a controlling terminal, then
899 a @code{SIGHUP} signal is sent to each process in the foreground job,
900 and the controlling terminal is disassociated from that session.
901 @xref{Job Control}.
902
903 @item
904 If termination of a process causes a process group to become orphaned,
905 and any member of that process group is stopped, then a @code{SIGHUP}
906 signal and a @code{SIGCONT} signal are sent to each process in the
907 group. @xref{Job Control}.
908 @end itemize