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