Update.
[glibc.git] / manual / startup.texi
blob1d903b49d7c1fb7e1ead40849c3a4ab33fd0db18
1 @node Process Startup, Processes, Signal Handling, Top
2 @c %MENU% Writing the beginning and end of your program
3 @chapter Process Startup and Termination
5 @cindex process
6 @dfn{Processes} are the primitive units for allocation of system
7 resources.  Each process has its own address space and (usually) one
8 thread of control.  A process executes a program; you can have multiple
9 processes executing the same program, but each process has its own copy
10 of the program within its own address space and executes it
11 independently of the other copies.
13 This chapter explains what your program should do to handle the startup
14 of a process, to terminate its process, and to receive information
15 (arguments and the environment) from the parent process.
17 @menu
18 * Program Arguments::           Parsing your program's command-line arguments.
19 * Environment Variables::       How to access parameters inherited from
20                                  a parent process.
21 * Program Termination::         How to cause a process to terminate and
22                                  return status information to its parent.
23 @end menu
25 @node Program Arguments
26 @section Program Arguments
27 @cindex program arguments
28 @cindex command line arguments
29 @cindex arguments, to program
31 @cindex program startup
32 @cindex startup of program
33 @cindex invocation of program
34 @cindex @code{main} function
35 @findex main
36 The system starts a C program by calling the function @code{main}.  It
37 is up to you to write a function named @code{main}---otherwise, you
38 won't even be able to link your program without errors.
40 In @w{ISO C} you can define @code{main} either to take no arguments, or to
41 take two arguments that represent the command line arguments to the
42 program, like this:
44 @smallexample
45 int main (int @var{argc}, char *@var{argv}[])
46 @end smallexample
48 @cindex argc (program argument count)
49 @cindex argv (program argument vector)
50 The command line arguments are the whitespace-separated tokens given in
51 the shell command used to invoke the program; thus, in @samp{cat foo
52 bar}, the arguments are @samp{foo} and @samp{bar}.  The only way a
53 program can look at its command line arguments is via the arguments of
54 @code{main}.  If @code{main} doesn't take arguments, then you cannot get
55 at the command line.
57 The value of the @var{argc} argument is the number of command line
58 arguments.  The @var{argv} argument is a vector of C strings; its
59 elements are the individual command line argument strings.  The file
60 name of the program being run is also included in the vector as the
61 first element; the value of @var{argc} counts this element.  A null
62 pointer always follows the last element: @code{@var{argv}[@var{argc}]}
63 is this null pointer.
65 For the command @samp{cat foo bar}, @var{argc} is 3 and @var{argv} has
66 three elements, @code{"cat"}, @code{"foo"} and @code{"bar"}.
68 In Unix systems you can define @code{main} a third way, using three arguments:
70 @smallexample
71 int main (int @var{argc}, char *@var{argv}[], char *@var{envp})
72 @end smallexample
74 The first two arguments are just the same.  The third argument
75 @var{envp} gives the process's environment; it is the same as the value
76 of @code{environ}.  @xref{Environment Variables}.  POSIX.1 does not
77 allow this three-argument form, so to be portable it is best to write
78 @code{main} to take two arguments, and use the value of @code{environ}.
80 @menu
81 * Argument Syntax::             By convention, options start with a hyphen.
82 * Parsing Program Arguments::   Ways to parse program options and arguments.
83 @end menu
85 @node Argument Syntax, Parsing Program Arguments, , Program Arguments
86 @subsection Program Argument Syntax Conventions
87 @cindex program argument syntax
88 @cindex syntax, for program arguments
89 @cindex command argument syntax
91 POSIX recommends these conventions for command line arguments.
92 @code{getopt} (@pxref{Getopt}) and @code{argp_parse} (@pxref{Argp}) make
93 it easy to implement them.
95 @itemize @bullet
96 @item
97 Arguments are options if they begin with a hyphen delimiter (@samp{-}).
99 @item
100 Multiple options may follow a hyphen delimiter in a single token if
101 the options do not take arguments.  Thus, @samp{-abc} is equivalent to
102 @samp{-a -b -c}.
104 @item
105 Option names are single alphanumeric characters (as for @code{isalnum};
106 @pxref{Classification of Characters}).
108 @item
109 Certain options require an argument.  For example, the @samp{-o} command
110 of the @code{ld} command requires an argument---an output file name.
112 @item
113 An option and its argument may or may not appear as separate tokens.  (In
114 other words, the whitespace separating them is optional.)  Thus,
115 @w{@samp{-o foo}} and @samp{-ofoo} are equivalent.
117 @item
118 Options typically precede other non-option arguments.
120 The implementations of @code{getopt} and @code{argp_parse} in the GNU C
121 library normally make it appear as if all the option arguments were
122 specified before all the non-option arguments for the purposes of
123 parsing, even if the user of your program intermixed option and
124 non-option arguments.  They do this by reordering the elements of the
125 @var{argv} array.  This behavior is nonstandard; if you want to suppress
126 it, define the @code{_POSIX_OPTION_ORDER} environment variable.
127 @xref{Standard Environment}.
129 @item
130 The argument @samp{--} terminates all options; any following arguments
131 are treated as non-option arguments, even if they begin with a hyphen.
133 @item
134 A token consisting of a single hyphen character is interpreted as an
135 ordinary non-option argument.  By convention, it is used to specify
136 input from or output to the standard input and output streams.
138 @item
139 Options may be supplied in any order, or appear multiple times.  The
140 interpretation is left up to the particular application program.
141 @end itemize
143 @cindex long-named options
144 GNU adds @dfn{long options} to these conventions.  Long options consist
145 of @samp{--} followed by a name made of alphanumeric characters and
146 dashes.  Option names are typically one to three words long, with
147 hyphens to separate words.  Users can abbreviate the option names as
148 long as the abbreviations are unique.
150 To specify an argument for a long option, write
151 @samp{--@var{name}=@var{value}}.  This syntax enables a long option to
152 accept an argument that is itself optional.
154 Eventually, the GNU system will provide completion for long option names
155 in the shell.
157 @node Parsing Program Arguments, , Argument Syntax, Program Arguments
158 @subsection Parsing Program Arguments
160 @cindex program arguments, parsing
161 @cindex command arguments, parsing
162 @cindex parsing program arguments
163 If the syntax for the command line arguments to your program is simple
164 enough, you can simply pick the arguments off from @var{argv} by hand.
165 But unless your program takes a fixed number of arguments, or all of the
166 arguments are interpreted in the same way (as file names, for example),
167 you are usually better off using @code{getopt} (@pxref{Getopt}) or
168 @code{argp_parse} (@pxref{Argp}) to do the parsing.
170 @code{getopt} is more standard (the short-option only version of it is a
171 part of the POSIX standard), but using @code{argp_parse} is often
172 easier, both for very simple and very complex option structures, because
173 it does more of the dirty work for you.
175 @menu
176 * Getopt::                      Parsing program options using @code{getopt}.
177 * Argp::                        Parsing program options using @code{argp_parse}.
178 * Suboptions::                  Some programs need more detailed options.
179 * Suboptions Example::          This shows how it could be done for @code{mount}.
180 @end menu
182 @c Getopt and argp start at the @section level so that there's
183 @c enough room for their internal hierarchy (mostly a problem with
184 @c argp).         -Miles
186 @include getopt.texi
187 @include argp.texi
189 @node Suboptions, Suboptions Example, Argp, Parsing Program Arguments
190 @c This is a @section so that it's at the same level as getopt and argp
191 @subsubsection Parsing of Suboptions
193 Having a single level of options is sometimes not enough.  There might
194 be too many options which have to be available or a set of options is
195 closely related.
197 For this case some programs use suboptions.  One of the most prominent
198 programs is certainly @code{mount}(8).  The @code{-o} option take one
199 argument which itself is a comma separated list of options.  To ease the
200 programming of code like this the function @code{getsubopt} is
201 available.
203 @comment stdlib.h
204 @deftypefun int getsubopt (char **@var{optionp}, const char* const *@var{tokens}, char **@var{valuep})
206 The @var{optionp} parameter must be a pointer to a variable containing
207 the address of the string to process.  When the function returns the
208 reference is updated to point to the next suboption or to the
209 terminating @samp{\0} character if there is no more suboption available.
211 The @var{tokens} parameter references an array of strings containing the
212 known suboptions.  All strings must be @samp{\0} terminated and to mark
213 the end a null pointer must be stored.  When @code{getsubopt} finds a
214 possible legal suboption it compares it with all strings available in
215 the @var{tokens} array and returns the index in the string as the
216 indicator.
218 In case the suboption has an associated value introduced by a @samp{=}
219 character, a pointer to the value is returned in @var{valuep}.  The
220 string is @samp{\0} terminated.  If no argument is available
221 @var{valuep} is set to the null pointer.  By doing this the caller can
222 check whether a necessary value is given or whether no unexpected value
223 is present.
225 In case the next suboption in the string is not mentioned in the
226 @var{tokens} array the starting address of the suboption including a
227 possible value is returned in @var{valuep} and the return value of the
228 function is @samp{-1}.
229 @end deftypefun
231 @node Suboptions Example, , Suboptions, Parsing Program Arguments
232 @subsection Parsing of Suboptions Example
234 The code which might appear in the @code{mount}(8) program is a perfect
235 example of the use of @code{getsubopt}:
237 @smallexample
238 @include subopt.c.texi
239 @end smallexample
242 @node Environment Variables
243 @section Environment Variables
245 @cindex environment variable
246 When a program is executed, it receives information about the context in
247 which it was invoked in two ways.  The first mechanism uses the
248 @var{argv} and @var{argc} arguments to its @code{main} function, and is
249 discussed in @ref{Program Arguments}.  The second mechanism uses
250 @dfn{environment variables} and is discussed in this section.
252 The @var{argv} mechanism is typically used to pass command-line
253 arguments specific to the particular program being invoked.  The
254 environment, on the other hand, keeps track of information that is
255 shared by many programs, changes infrequently, and that is less
256 frequently used.
258 The environment variables discussed in this section are the same
259 environment variables that you set using assignments and the
260 @code{export} command in the shell.  Programs executed from the shell
261 inherit all of the environment variables from the shell.
262 @c !!! xref to right part of bash manual when it exists
264 @cindex environment
265 Standard environment variables are used for information about the user's
266 home directory, terminal type, current locale, and so on; you can define
267 additional variables for other purposes.  The set of all environment
268 variables that have values is collectively known as the
269 @dfn{environment}.
271 Names of environment variables are case-sensitive and must not contain
272 the character @samp{=}.  System-defined environment variables are
273 invariably uppercase.
275 The values of environment variables can be anything that can be
276 represented as a string.  A value must not contain an embedded null
277 character, since this is assumed to terminate the string.
280 @menu
281 * Environment Access::          How to get and set the values of
282                                  environment variables.
283 * Standard Environment::        These environment variables have
284                                  standard interpretations.
285 @end menu
287 @node Environment Access
288 @subsection Environment Access
289 @cindex environment access
290 @cindex environment representation
292 The value of an environment variable can be accessed with the
293 @code{getenv} function.  This is declared in the header file
294 @file{stdlib.h}.  All of the following functions can be safely used in
295 multi-threaded programs.  It is made sure that concurrent modifications
296 to the environment do not lead to errors.
297 @pindex stdlib.h
299 @comment stdlib.h
300 @comment ISO
301 @deftypefun {char *} getenv (const char *@var{name})
302 This function returns a string that is the value of the environment
303 variable @var{name}.  You must not modify this string.  In some non-Unix
304 systems not using the GNU library, it might be overwritten by subsequent
305 calls to @code{getenv} (but not by any other library function).  If the
306 environment variable @var{name} is not defined, the value is a null
307 pointer.
308 @end deftypefun
311 @comment stdlib.h
312 @comment SVID
313 @deftypefun int putenv (const char *@var{string})
314 The @code{putenv} function adds or removes definitions from the environment.
315 If the @var{string} is of the form @samp{@var{name}=@var{value}}, the
316 definition is added to the environment.  Otherwise, the @var{string} is
317 interpreted as the name of an environment variable, and any definition
318 for this variable in the environment is removed.
320 This function is part of the extended Unix interface.  Since it was also
321 available in old SVID libraries you should define either
322 @var{_XOPEN_SOURCE} or @var{_SVID_SOURCE} before including any header.
323 @end deftypefun
326 @comment stdlib.h
327 @comment BSD
328 @deftypefun int setenv (const char *@var{name}, const char *@var{value}, int @var{replace})
329 The @code{setenv} function can be used to add a new definition to the
330 environment.  The entry with the name @var{name} is replaced by the
331 value @samp{@var{name}=@var{value}}.  Please note that this is also true
332 if @var{value} is the empty string.  A null pointer for the @var{value}
333 parameter is illegal.  If the environment already contains an entry with
334 key @var{name} the @var{replace} parameter controls the action.  If
335 replace is zero, nothing happens.  otherwise the old entry is replaced
336 by the new one.
338 Please note that you cannot remove an entry completely using this function.
340 This function is part of the BSD library.  The GNU C Library provides
341 this function for compatibility but it may not be available on other
342 systems.
343 @end deftypefun
345 @comment stdlib.h
346 @comment BSD
347 @deftypefun void unsetenv (const char *@var{name})
348 Using this function one can remove an entry completely from the
349 environment.  If the environment contains an entry with the key
350 @var{name} this whole entry is removed.  A call to this function is
351 equivalent to a call to @code{putenv} when the @var{value} part of the
352 string is empty.
354 This function is part of the BSD library.  The GNU C Library provides
355 this function for compatibility but it may not be available on other
356 systems.
357 @end deftypefun
359 There is one more function to modify the whole environment.  This
360 function is said to be used in the POSIX.9 (POSIX bindings for Fortran
361 77) and so one should expect it did made it into POSIX.1.  But this
362 never happened.  But we still provide this function as a GNU extension
363 to enable writing standard compliant Fortran environments.
365 @comment stdlib.h
366 @comment GNU
367 @deftypefun int clearenv (void)
368 The @code{clearenv} function removes all entries from the environment.
369 Using @code{putenv} and @code{setenv} new entries can be added again
370 later.
372 If the function is successful it returns @code{0}.  Otherwise the return
373 value is nonzero.
374 @end deftypefun
377 You can deal directly with the underlying representation of environment
378 objects to add more variables to the environment (for example, to
379 communicate with another program you are about to execute;
380 @pxref{Executing a File}).
382 @comment unistd.h
383 @comment POSIX.1
384 @deftypevar {char **} environ
385 The environment is represented as an array of strings.  Each string is
386 of the format @samp{@var{name}=@var{value}}.  The order in which
387 strings appear in the environment is not significant, but the same
388 @var{name} must not appear more than once.  The last element of the
389 array is a null pointer.
391 This variable is declared in the header file @file{unistd.h}.
393 If you just want to get the value of an environment variable, use
394 @code{getenv}.
395 @end deftypevar
397 Unix systems, and the GNU system, pass the initial value of
398 @code{environ} as the third argument to @code{main}.
399 @xref{Program Arguments}.
401 @node Standard Environment
402 @subsection Standard Environment Variables
403 @cindex standard environment variables
405 These environment variables have standard meanings.  This doesn't mean
406 that they are always present in the environment; but if these variables
407 @emph{are} present, they have these meanings.  You shouldn't try to use
408 these environment variable names for some other purpose.
410 @comment Extra blank lines make it look better.
411 @table @code
412 @item HOME
413 @cindex @code{HOME} environment variable
414 @cindex home directory
416 This is a string representing the user's @dfn{home directory}, or
417 initial default working directory.
419 The user can set @code{HOME} to any value.
420 If you need to make sure to obtain the proper home directory
421 for a particular user, you should not use @code{HOME}; instead,
422 look up the user's name in the user database (@pxref{User Database}).
424 For most purposes, it is better to use @code{HOME}, precisely because
425 this lets the user specify the value.
427 @c !!! also USER
428 @item LOGNAME
429 @cindex @code{LOGNAME} environment variable
431 This is the name that the user used to log in.  Since the value in the
432 environment can be tweaked arbitrarily, this is not a reliable way to
433 identify the user who is running a process; a function like
434 @code{getlogin} (@pxref{Who Logged In}) is better for that purpose.
436 For most purposes, it is better to use @code{LOGNAME}, precisely because
437 this lets the user specify the value.
439 @item PATH
440 @cindex @code{PATH} environment variable
442 A @dfn{path} is a sequence of directory names which is used for
443 searching for a file.  The variable @code{PATH} holds a path used
444 for searching for programs to be run.
446 The @code{execlp} and @code{execvp} functions (@pxref{Executing a File})
447 use this environment variable, as do many shells and other utilities
448 which are implemented in terms of those functions.
450 The syntax of a path is a sequence of directory names separated by
451 colons.  An empty string instead of a directory name stands for the
452 current directory (@pxref{Working Directory}).
454 A typical value for this environment variable might be a string like:
456 @smallexample
457 :/bin:/etc:/usr/bin:/usr/new/X11:/usr/new:/usr/local/bin
458 @end smallexample
460 This means that if the user tries to execute a program named @code{foo},
461 the system will look for files named @file{foo}, @file{/bin/foo},
462 @file{/etc/foo}, and so on.  The first of these files that exists is
463 the one that is executed.
465 @c !!! also TERMCAP
466 @item TERM
467 @cindex @code{TERM} environment variable
469 This specifies the kind of terminal that is receiving program output.
470 Some programs can make use of this information to take advantage of
471 special escape sequences or terminal modes supported by particular kinds
472 of terminals.  Many programs which use the termcap library
473 (@pxref{Finding a Terminal Description,Find,,termcap,The Termcap Library
474 Manual}) use the @code{TERM} environment variable, for example.
476 @item TZ
477 @cindex @code{TZ} environment variable
479 This specifies the time zone.  @xref{TZ Variable}, for information about
480 the format of this string and how it is used.
482 @item LANG
483 @cindex @code{LANG} environment variable
485 This specifies the default locale to use for attribute categories where
486 neither @code{LC_ALL} nor the specific environment variable for that
487 category is set.  @xref{Locales}, for more information about
488 locales.
490 @ignore
491 @c I doubt this really exists
492 @item LC_ALL
493 @cindex @code{LC_ALL} environment variable
495 This is similar to the @code{LANG} environment variable.  However, its
496 value takes precedence over any values provided for the individual
497 attribute category environment variables, or for the @code{LANG}
498 environment variable.
499 @end ignore
501 @item LC_ALL
502 @cindex @code{LC_ALL} environment variable
504 If this environment variable is set it overrides the selection for all
505 the locales done using the other @code{LC_*} environment variables.  The
506 value of the other @code{LC_*} environment variables is simply ignored
507 in this case.
509 @item LC_COLLATE
510 @cindex @code{LC_COLLATE} environment variable
512 This specifies what locale to use for string sorting.
514 @item LC_CTYPE
515 @cindex @code{LC_CTYPE} environment variable
517 This specifies what locale to use for character sets and character
518 classification.
520 @item LC_MESSAGES
521 @cindex @code{LC_MESSAGES} environment variable
523 This specifies what locale to use for printing messages and to parse
524 responses.
526 @item LC_MONETARY
527 @cindex @code{LC_MONETARY} environment variable
529 This specifies what locale to use for formatting monetary values.
531 @item LC_NUMERIC
532 @cindex @code{LC_NUMERIC} environment variable
534 This specifies what locale to use for formatting numbers.
536 @item LC_TIME
537 @cindex @code{LC_TIME} environment variable
539 This specifies what locale to use for formatting date/time values.
541 @item NLSPATH
542 @cindex @code{NLSPATH} environment variable
544 This specifies the directories in which the @code{catopen} function
545 looks for message translation catalogs.
547 @item _POSIX_OPTION_ORDER
548 @cindex @code{_POSIX_OPTION_ORDER} environment variable.
550 If this environment variable is defined, it suppresses the usual
551 reordering of command line arguments by @code{getopt} and
552 @code{argp_parse}.  @xref{Argument Syntax}.
554 @c !!! GNU also has COREFILE, CORESERVER, EXECSERVERS
555 @end table
557 @node Program Termination
558 @section Program Termination
559 @cindex program termination
560 @cindex process termination
562 @cindex exit status value
563 The usual way for a program to terminate is simply for its @code{main}
564 function to return.  The @dfn{exit status value} returned from the
565 @code{main} function is used to report information back to the process's
566 parent process or shell.
568 A program can also terminate normally by calling the @code{exit}
569 function.
571 In addition, programs can be terminated by signals; this is discussed in
572 more detail in @ref{Signal Handling}.  The @code{abort} function causes
573 a signal that kills the program.
575 @menu
576 * Normal Termination::          If a program calls @code{exit}, a
577                                  process terminates normally.
578 * Exit Status::                 The @code{exit status} provides information
579                                  about why the process terminated.
580 * Cleanups on Exit::            A process can run its own cleanup
581                                  functions upon normal termination.
582 * Aborting a Program::          The @code{abort} function causes
583                                  abnormal program termination.
584 * Termination Internals::       What happens when a process terminates.
585 @end menu
587 @node Normal Termination
588 @subsection Normal Termination
590 A process terminates normally when the program calls @code{exit}.
591 Returning from @code{main} is equivalent to calling @code{exit}, and
592 the value that @code{main} returns is used as the argument to @code{exit}.
594 @comment stdlib.h
595 @comment ISO
596 @deftypefun void exit (int @var{status})
597 The @code{exit} function terminates the process with status
598 @var{status}.  This function does not return.
599 @end deftypefun
601 Normal termination causes the following actions:
603 @enumerate
604 @item
605 Functions that were registered with the @code{atexit} or @code{on_exit}
606 functions are called in the reverse order of their registration.  This
607 mechanism allows your application to specify its own ``cleanup'' actions
608 to be performed at program termination.  Typically, this is used to do
609 things like saving program state information in a file, or unlocking
610 locks in shared data bases.
612 @item
613 All open streams are closed, writing out any buffered output data.  See
614 @ref{Closing Streams}.  In addition, temporary files opened
615 with the @code{tmpfile} function are removed; see @ref{Temporary Files}.
617 @item
618 @code{_exit} is called, terminating the program.  @xref{Termination Internals}.
619 @end enumerate
621 @node Exit Status
622 @subsection Exit Status
623 @cindex exit status
625 When a program exits, it can return to the parent process a small
626 amount of information about the cause of termination, using the
627 @dfn{exit status}.  This is a value between 0 and 255 that the exiting
628 process passes as an argument to @code{exit}.
630 Normally you should use the exit status to report very broad information
631 about success or failure.  You can't provide a lot of detail about the
632 reasons for the failure, and most parent processes would not want much
633 detail anyway.
635 There are conventions for what sorts of status values certain programs
636 should return.  The most common convention is simply 0 for success and 1
637 for failure.  Programs that perform comparison use a different
638 convention: they use status 1 to indicate a mismatch, and status 2 to
639 indicate an inability to compare.  Your program should follow an
640 existing convention if an existing convention makes sense for it.
642 A general convention reserves status values 128 and up for special
643 purposes.  In particular, the value 128 is used to indicate failure to
644 execute another program in a subprocess.  This convention is not
645 universally obeyed, but it is a good idea to follow it in your programs.
647 @strong{Warning:} Don't try to use the number of errors as the exit
648 status.  This is actually not very useful; a parent process would
649 generally not care how many errors occurred.  Worse than that, it does
650 not work, because the status value is truncated to eight bits.
651 Thus, if the program tried to report 256 errors, the parent would
652 receive a report of 0 errors---that is, success.
654 For the same reason, it does not work to use the value of @code{errno}
655 as the exit status---these can exceed 255.
657 @strong{Portability note:} Some non-POSIX systems use different
658 conventions for exit status values.  For greater portability, you can
659 use the macros @code{EXIT_SUCCESS} and @code{EXIT_FAILURE} for the
660 conventional status value for success and failure, respectively.  They
661 are declared in the file @file{stdlib.h}.
662 @pindex stdlib.h
664 @comment stdlib.h
665 @comment ISO
666 @deftypevr Macro int EXIT_SUCCESS
667 This macro can be used with the @code{exit} function to indicate
668 successful program completion.
670 On POSIX systems, the value of this macro is @code{0}.  On other
671 systems, the value might be some other (possibly non-constant) integer
672 expression.
673 @end deftypevr
675 @comment stdlib.h
676 @comment ISO
677 @deftypevr Macro int EXIT_FAILURE
678 This macro can be used with the @code{exit} function to indicate
679 unsuccessful program completion in a general sense.
681 On POSIX systems, the value of this macro is @code{1}.  On other
682 systems, the value might be some other (possibly non-constant) integer
683 expression.  Other nonzero status values also indicate failures.  Certain
684 programs use different nonzero status values to indicate particular
685 kinds of "non-success".  For example, @code{diff} uses status value
686 @code{1} to mean that the files are different, and @code{2} or more to
687 mean that there was difficulty in opening the files.
688 @end deftypevr
690 @node Cleanups on Exit
691 @subsection Cleanups on Exit
693 Your program can arrange to run its own cleanup functions if normal
694 termination happens.  If you are writing a library for use in various
695 application programs, then it is unreliable to insist that all
696 applications call the library's cleanup functions explicitly before
697 exiting.  It is much more robust to make the cleanup invisible to the
698 application, by setting up a cleanup function in the library itself
699 using @code{atexit} or @code{on_exit}.
701 @comment stdlib.h
702 @comment ISO
703 @deftypefun int atexit (void (*@var{function}) (void))
704 The @code{atexit} function registers the function @var{function} to be
705 called at normal program termination.  The @var{function} is called with
706 no arguments.
708 The return value from @code{atexit} is zero on success and nonzero if
709 the function cannot be registered.
710 @end deftypefun
712 @comment stdlib.h
713 @comment SunOS
714 @deftypefun int on_exit (void (*@var{function})(int @var{status}, void *@var{arg}), void *@var{arg})
715 This function is a somewhat more powerful variant of @code{atexit}.  It
716 accepts two arguments, a function @var{function} and an arbitrary
717 pointer @var{arg}.  At normal program termination, the @var{function} is
718 called with two arguments:  the @var{status} value passed to @code{exit},
719 and the @var{arg}.
721 This function is included in the GNU C library only for compatibility
722 for SunOS, and may not be supported by other implementations.
723 @end deftypefun
725 Here's a trivial program that illustrates the use of @code{exit} and
726 @code{atexit}:
728 @smallexample
729 @include atexit.c.texi
730 @end smallexample
732 @noindent
733 When this program is executed, it just prints the message and exits.
735 @node Aborting a Program
736 @subsection Aborting a Program
737 @cindex aborting a program
739 You can abort your program using the @code{abort} function.  The prototype
740 for this function is in @file{stdlib.h}.
741 @pindex stdlib.h
743 @comment stdlib.h
744 @comment ISO
745 @deftypefun void abort (void)
746 The @code{abort} function causes abnormal program termination.  This
747 does not execute cleanup functions registered with @code{atexit} or
748 @code{on_exit}.
750 This function actually terminates the process by raising a
751 @code{SIGABRT} signal, and your program can include a handler to
752 intercept this signal; see @ref{Signal Handling}.
753 @end deftypefun
755 @c Put in by rms.  Don't remove.
756 @cartouche
757 @strong{Future Change Warning:} Proposed Federal censorship regulations
758 may prohibit us from giving you information about the possibility of
759 calling this function.  We would be required to say that this is not an
760 acceptable way of terminating a program.
761 @end cartouche
763 @node Termination Internals
764 @subsection Termination Internals
766 The @code{_exit} function is the primitive used for process termination
767 by @code{exit}.  It is declared in the header file @file{unistd.h}.
768 @pindex unistd.h
770 @comment unistd.h
771 @comment POSIX.1
772 @deftypefun void _exit (int @var{status})
773 The @code{_exit} function is the primitive for causing a process to
774 terminate with status @var{status}.  Calling this function does not
775 execute cleanup functions registered with @code{atexit} or
776 @code{on_exit}.
777 @end deftypefun
779 When a process terminates for any reason---either by an explicit
780 termination call, or termination as a result of a signal---the
781 following things happen:
783 @itemize @bullet
784 @item
785 All open file descriptors in the process are closed.  @xref{Low-Level I/O}.
786 Note that streams are not flushed automatically when the process
787 terminates; see @ref{I/O on Streams}.
789 @item
790 The low-order 8 bits of the return status code are saved to be reported
791 back to the parent process via @code{wait} or @code{waitpid}; see
792 @ref{Process Completion}.
794 @item
795 Any child processes of the process being terminated are assigned a new
796 parent process.  (On most systems, including GNU, this is the @code{init}
797 process, with process ID 1.)
799 @item
800 A @code{SIGCHLD} signal is sent to the parent process.
802 @item
803 If the process is a session leader that has a controlling terminal, then
804 a @code{SIGHUP} signal is sent to each process in the foreground job,
805 and the controlling terminal is disassociated from that session.
806 @xref{Job Control}.
808 @item
809 If termination of a process causes a process group to become orphaned,
810 and any member of that process group is stopped, then a @code{SIGHUP}
811 signal and a @code{SIGCONT} signal are sent to each process in the
812 group.  @xref{Job Control}.
813 @end itemize