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