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