@Go to the ‰ŠP�”›first@�”˜, ‰ŠP�”›previous@�”˜, ‰ŠP�”›next@�”˜, ‰ŠP�”›last@�”˜ section, ‰ŠP�”›table of contents@�”˜.
Œ

ˆ‰SEC389Št�”›Process Startup and Termination

‰IDX1791ŠB�”˜Processes@ are the primitive units for allocation of system resources. Each process has its own address space and (usually) one thread of control. A process executes a program; you can have multiple processes executing the same program, but each process has its own copy of the program within its own address space and executes it independently of the other copies.
This chapter explains what your program should do to handle the startup of a process, to terminate its process, and to receive information (arguments and the environment) from the parent process.
ˆ‰SEC390Št�”›Program Arguments

‰IDX1792Š‰IDX1793Š‰IDX1794Š
‰IDX1795Š‰IDX1796Š‰IDX1797Š‰IDX1798Š‰IDX1799Š@�”˜The system starts a C program by calling the function Hmain@. It is up to you to write a function named Hmain@---otherwise, you won't even be able to link your program without errors.
In ISO C you can define Hmain@ either to take no arguments, or to take two arguments that represent the command line arguments to the program, like this: int main (int Bargc@, char *Bargv@[])
‰IDX1800Š‰IDX1801Š@�”˜The command line arguments are the whitespace-separated tokens given in the shell command used to invoke the program; thus, in H`cat foo bar'@, the arguments are H`foo'@ and H`bar'@. The only way a program can look at its command line arguments is via the arguments of Hmain@. If Hmain@ doesn't take arguments, then you cannot get at the command line.
The value of the Bargc@ argument is the number of command line arguments. The Bargv@ argument is a vector of C strings; its elements are the individual command line argument strings. The file name of the program being run is also included in the vector as the first element; the value of Bargc@ counts this element. A null pointer always follows the last element: JargvH[JargcH]@ is this null pointer.
For the command H`cat foo bar'@, Bargc@ is 3 and Bargv@ has three elements, H"cat"@, H"foo"@ and H"bar"@.
If the syntax for the command line arguments to your program is simple enough, you can simply pick the arguments off from Bargv@ by hand. But unless your program takes a fixed number of arguments, or all of the arguments are interpreted in the same way (as file names, for example), you are usually better off using Hgetopt@ to do the parsing.
In Unix systems you can define Hmain@ a third way, using three arguments: int main (int Bargc@, char *Bargv@[], char *Benvp@)
The first two arguments are just the same. The third argument Benvp@ gives the process's environment; it is the same as the value of Henviron@. See section ‰ŠP�”›Environment Variables@�”˜. POSIX.1 does not allow this three-argument form, so to be portable it is best to write Hmain@ to take two arguments, and use the value of Henviron@.
ˆ‰SEC391ŠT�”›Program Argument Syntax Conventions

‰IDX1802Š‰IDX1803Š‰IDX1804Š
@�”˜POSIX recommends these conventions for command line arguments. Hgetopt@ (see section ‰ŠP�”›Parsing Program Options@�”˜) makes it easy to implement them. þÂ
• Arguments are options if they begin with a hyphen delimiter (H`-'@).
• Multiple options may follow a hyphen delimiter in a single token if the options do not take arguments. Thus, H`-abc'@ is equivalent to H`-a -b -c'@.
• Option names are single alphanumeric characters (as for Hisalnum@; see section ‰ŠP�”›Classification of Characters@�”˜).
• Certain options require an argument. For example, the H`-o'@ command of the Hld@ command requires an argument--an output file name.
• An option and its argument may or may not appear as separate tokens. (In other words, the whitespace separating them is optional.) Thus, H`-o foo'@ and H`-ofoo'@ are equivalent.
• Options typically precede other non-option arguments. The implementation of Hgetopt@ in the GNU C library normally makes it appear as if all the option arguments were specified before all the non-option arguments for the purposes of parsing, even if the user of your program intermixed option and non-option arguments. It does this by reordering the elements of the Bargv@ array. This behavior is nonstandard; if you want to suppress it, define the H_POSIX_OPTION_ORDER@ environment variable. See section ‰ŠP�”›Standard Environment Variables@�”˜.
• The argument H`--'@ terminates all options; any following arguments are treated as non-option arguments, even if they begin with a hyphen.
• A token consisting of a single hyphen character is interpreted as an ordinary non-option argument. By convention, it is used to specify input from or output to the standard input and output streams.
• Options may be supplied in any order, or appear multiple times. The interpretation is left up to the particular application program.Àð
‰IDX1805Š@�”˜GNU adds Blong options@ to these conventions. Long options consist of H`--'@ followed by a name made of alphanumeric characters and dashes. Option names are typically one to three words long, with hyphens to separate words. Users can abbreviate the option names as long as the abbreviations are unique.
To specify an argument for a long option, write H`--JnameH=JvalueH'@. This syntax enables a long option to accept an argument that is itself optional.
Eventually, the GNU system will provide completion for long option names in the shell.
ˆ‰SEC392ŠT�”›Parsing Program Options

‰IDX1806Š‰IDX1807Š‰IDX1808Š
@�”˜Here are the details about how to call the Hgetopt@ function. To use this facility, your program must include the header file H`unistd.h'@. ‰IDX1809Š

A�”˜Variable:@ int Dopterr
Â‰IDX1810Š@�”˜If the value of this variable is nonzero, then Hgetopt@ prints an error message to the standard error stream if it encounters an unknown option character or an option with a missing required argument. This is the default behavior. If you set this variable to zero, Hgetopt@ does not print any messages, but it still returns the character H?@ to indicate an error.À

AVariable:@ int Doptopt
Â‰IDX1811Š@�”˜When Hgetopt@ encounters an unknown option character or an option with a missing required argument, it stores that option character in this variable. You can use this for providing your own diagnostic messages.À

AVariable:@ int Doptind
Â‰IDX1812Š@�”˜This variable is set by Hgetopt@ to the index of the next element of the Bargv@ array to be processed. Once Hgetopt@ has found all of the option arguments, you can use this variable to determine where the remaining non-option arguments begin. The initial value of this variable is H1@.À

AVariable:@ char * Doptarg
Â‰IDX1813Š@�”˜This variable is set by Hgetopt@ to point at the value of the option argument, for those options that accept arguments.À

AFunction:@ int Dgetopt@ B(int Bargc@, char **Bargv@, const char *Boptions@)
Â‰IDX1814Š@�”˜The Hgetopt@ function gets the next option argument from the argument list specified by the Bargv@ and Bargc@ arguments. Normally these values come directly from the arguments received by Hmain@.
The Boptions@ argument is a string that specifies the option characters that are valid for this program. An option character in this string can be followed by a colon (H`:'@) to indicate that it takes a required argument.
If the Boptions@ argument string begins with a hyphen (H`-'@), this is treated specially. It permits arguments that are not options to be returned as if they were associated with option character H`\0'@.
The Hgetopt@ function returns the option character for the next command line option. When no more option arguments are available, it returns H-1@. There may still be more non-option arguments; you must compare the external variable Hoptind@ against the Bargc@ parameter to check this.
If the option has an argument, Hgetopt@ returns the argument by storing it in the variable Boptarg@. You don't ordinarily need to copy the Hoptarg@ string, since it is a pointer into the original Bargv@ array, not into a static area that might be overwritten.
If Hgetopt@ finds an option character in Bargv@ that was not included in Boptions@, or a missing option argument, it returns H`?'@ and sets the external variable Hoptopt@ to the actual option character. If the first character of Boptions@ is a colon (H`:'@), then Hgetopt@ returns H`:'@ instead of H`?'@ to indicate a missing option argument. In addition, if the external variable Hopterr@ is nonzero (which is the default), Hgetopt@ prints an error message.À

ˆ‰SEC393ŠT�”›Example of Parsing Arguments with \getopt

@�”˜Here is an example showing how Hgetopt@ is typically used. The key points to notice are: þÂ
• Normally, Hgetopt@ is called in a loop. When Hgetopt@ returns H-1@, indicating no more options are present, the loop terminates.
• A Hswitch@ statement is used to dispatch on the return value from Hgetopt@. In typical use, each case just sets a variable that is used later in the program.
• A second loop is used to process the remaining non-option arguments.Àð #include <unistd.h>
#include <stdio.h>

int
main (int argc, char **argv)
{
int aflag = 0;
int bflag = 0;
char *cvalue = NULL;
int index;
int c;

opterr = 0;

while ((c = getopt (argc, argv, "abc:")) != -1)
switch (c)
{
case 'a':
aflag = 1;
break;
case 'b':
bflag = 1;
break;
case 'c':
cvalue = optarg;
break;
case '?':
if (isprint (optopt))
fprintf (stderr, "Unknown option `-%c'.\n", optopt);
else
fprintf (stderr,
"Unknown option character `\\x%x'.\n",
optopt);
return 1;
default:
abort ();
}

printf ("aflag = %d, bflag = %d, cvalue = %s\n", aflag, bflag, cvalue);

for (index = optind; index < argc; index++)
printf ("Non-option argument %s\n", argv[index]);
return 0;
}
Here are some examples showing what this program prints with different combinations of arguments: % testopt
aflag = 0, bflag = 0, cvalue = (null)

% testopt -a -b
aflag = 1, bflag = 1, cvalue = (null)

% testopt -ab
aflag = 1, bflag = 1, cvalue = (null)

% testopt -c foo
aflag = 0, bflag = 0, cvalue = foo

% testopt -cfoo
aflag = 0, bflag = 0, cvalue = foo

% testopt arg1
aflag = 0, bflag = 0, cvalue = (null)
Non-option argument arg1

% testopt -a arg1
aflag = 1, bflag = 0, cvalue = (null)
Non-option argument arg1

% testopt -c foo arg1
aflag = 0, bflag = 0, cvalue = foo
Non-option argument arg1

% testopt -a -- -b
aflag = 1, bflag = 0, cvalue = (null)
Non-option argument -b

% testopt -a -
aflag = 1, bflag = 0, cvalue = (null)
Non-option argument -
ˆ‰SEC394ŠT�”›Parsing Long Options

@�”˜To accept GNU-style long options as well as single-character options, use Hgetopt_long@ instead of Hgetopt@. This function is declared in H`getopt.h'@, not H`unistd.h'@. You should make every program accept long options if it uses any options, for this takes little extra work and helps beginners remember how to use the program.

AData Type:@ Dstruct option
Â‰IDX1815Š@�”˜This structure describes a single long option name for the sake of Hgetopt_long@. The argument Blongopts@ must be an array of these structures, one for each long option. Terminate the array with an element containing all zeros.
The Hstruct option@ structure has these fields:
Hconst char *name
Ä@This field is the name of the option. It is a string.
ÂHint has_arg
Ä@This field says whether the option takes an argument. It is an integer, and there are three legitimate values: Hno_argument@, Hrequired_argument@ and Hoptional_argument@.
ÂHint *flag
Ä
ÂHint val
Ä@These fields control how to report or act on the option when it occurs. If Hflag@ is a null pointer, then the Hval@ is a value which identifies this option. Often these values are chosen to uniquely identify particular long options. If Hflag@ is not a null pointer, it should be the address of an Hint@ variable which is the flag for this option. The value in Hval@ is the value to store in the flag to indicate that the option was seen.Â
À

AFunction:@ int Dgetopt_long@ B(int Bargc@, char **Bargv@, const char *Bshortopts@, struct option *Blongopts@, int *Bindexptr@)
Â‰IDX1816Š@�”˜Decode options from the vector Bargv@ (whose length is Bargc@). The argument Bshortopts@ describes the short options to accept, just as it does in Hgetopt@. The argument Blongopts@ describes the long options to accept (see above).
When Hgetopt_long@ encounters a short option, it does the same thing that Hgetopt@ would do: it returns the character code for the option, and stores the options argument (if it has one) in Hoptarg@.
When Hgetopt_long@ encounters a long option, it takes actions based on the Hflag@ and Hval@ fields of the definition of that option.
If Hflag@ is a null pointer, then Hgetopt_long@ returns the contents of Hval@ to indicate which option it found. You should arrange distinct values in the Hval@ field for options with different meanings, so you can decode these values after Hgetopt_long@ returns. If the long option is equivalent to a short option, you can use the short option's character code in Hval@.
If Hflag@ is not a null pointer, that means this option should just set a flag in the program. The flag is a variable of type Hint@ that you define. Put the address of the flag in the Hflag@ field. Put in the Hval@ field the value you would like this option to store in the flag. In this case, Hgetopt_long@ returns H0@.
For any long option, Hgetopt_long@ tells you the index in the array Blongopts@ of the options definition, by storing it into H*Jindexptr@. You can get the name of the option with JlongoptsH[*JindexptrH].name@. So you can distinguish among long options either by the values in their Hval@ fields or by their indices. You can also distinguish in this way among long options that set flags.
When a long option has an argument, Hgetopt_long@ puts the argument value in the variable Hoptarg@ before returning. When the option has no argument, the value in Hoptarg@ is a null pointer. This is how you can tell whether an optional argument was supplied.
When Hgetopt_long@ has no more options to handle, it returns H-1@, and leaves in the variable Hoptind@ the index in Bargv@ of the next remaining argument.À

ˆ‰SEC395ŠT�”›Example of Parsing Long Options
@�”˜#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>

/* Flag set by H`--verbose'@. */
static int verbose_flag;

int
main (argc, argv)
int argc;
char **argv;
{
int c;

while (1)
{
static struct option long_options[] =
{
/* These options set a flag. */
{"verbose", 0, &verbose_flag, 1},
{"brief", 0, &verbose_flag, 0},
/* These options don't set a flag.
We distinguish them by their indices. */
{"add", 1, 0, 0},
{"append", 0, 0, 0},
{"delete", 1, 0, 0},
{"create", 0, 0, 0},
{"file", 1, 0, 0},
{0, 0, 0, 0}
};
/* Hgetopt_long@ stores the option index here. */
int option_index = 0;

c = getopt_long (argc, argv, "abc:d:",
long_options, &option_index);

/* Detect the end of the options. */
if (c == -1)
break;

switch (c)
{
case 0:
/* If this option set a flag, do nothing else now. */
if (long_options[option_index].flag != 0)
break;
printf ("option %s", long_options[option_index].name);
if (optarg)
printf (" with arg %s", optarg);
printf ("\n");
break;

case 'a':
puts ("option -a\n");
break;

case 'b':
puts ("option -b\n");
break;

case 'c':
printf ("option -c with value `%s'\n", optarg);
break;

case 'd':
printf ("option -d with value `%s'\n", optarg);
break;

case '?':
/* Hgetopt_long@ already printed an error message. */
break;

default:
abort ();
}
}

/* Instead of reporting H`--verbose'
@ and H`--brief'@ as they are encountered,
we report the final status resulting from them. */
if (verbose_flag)
puts ("verbose flag is set");

/* Print any remaining command line arguments (not options). */
if (optind < argc)
{
printf ("non-option ARGV-elements: ");
while (optind < argc)
printf ("%s ", argv[optind++]);
putchar ('\n');
}

exit (0);
}
ˆ‰SEC396ŠT�”›Parsing of Suboptions

@�”˜Having a single level of options is sometimes not enough. There might be too many options which have to be available or a set of options is closely related.
For this case some programs use suboptions. One of the most prominent programs is certainly Hmount@(8). The H-o@ option take one argument which itself is a comma separated list of options. To ease the programming of code like this the function Hgetsubopt@ is available.

AFunction:@ int Dgetsubopt@ B(char **Boptionp@, const char* const *Btokens@, char **Bvaluep@)
Â‰IDX1817Š
@�”˜The Boptionp@ parameter must be a pointer to a variable containing the address of the string to process. When the function returns the reference is updated to point to the next suboption or to the terminating H`\0'@ character if there is no more suboption available.
The Btokens@ parameter references an array of strings containing the known suboptions. All strings must be H`\0'@ terminated and to mark the end a null pointer must be stored. When Hgetsubopt@ finds a possible legal suboption it compares it with all strings available in the Btokens@ array and returns the index in the string as the indicator.
In case the suboption has an associated value introduced by a H`='@ character, a pointer to the value is returned in Bvaluep@. The string is H`\0'@ terminated. If no argument is available Bvaluep@ is set to the null pointer. By doing this the caller can check whether a necessary value is given or whether no unexpected value is present.
In case the next suboption in the string is not mentioned in the Btokens@ array the starting address of the suboption including a possible value is returned in Bvaluep@ and the return value of the function is H`-1'@.À

ˆ‰SEC397ŠT�”›Parsing of Suboptions Example

@�”˜The code which might appear in the Hmount@(8) program is a perfect example of the use of Hgetsubopt@: #include <stdio.h>
#include <stdlib.h>

int do_all;
const char *type;
int read_size;
int write_size;
int read_only;

enum
{
RO_OPTION = 0,
RW_OPTION,
READ_SIZE_OPTION,
WRITE_SIZE_OPTION
};

const char *mount_opts[] =
{
[RO_OPTION] = "ro",
[RW_OPTION] = "rw",
[READ_SIZE_OPTION] = "rsize",
[WRITE_SIZE_OPTION] = "wsize"
};

int
main (int argc, char *argv[])
{
char *subopts, *value;
int opt;

while ((opt = getopt (argc, argv, "at:o:")) != -1)
switch (opt)
{
case 'a':
do_all = 1;
break;
case 't':
type = optarg;
break;
case 'o':
subopts = optarg;
while (*subopts != '\0')
switch (getsubopt (&subopts, mount_opts, &value))
{
case RO_OPTION:
read_only = 1;
break;
case RW_OPTION:
read_only = 0;
break;
case READ_SIZE_OPTION:
if (value == NULL)
abort ();
read_size = atoi (value);
break;
case WRITE_SIZE_OPTION:
if (value == NULL)
abort ();
write_size = atoi (value);
break;
default:
/* Unknown suboption. */
printf ("Unknown suboption `%s'\n", value);
break;
}
break;
default:
abort ();
}

/* Do the real work. */

return 0;
}
ˆ‰SEC398Št�”›Environment Variables

‰IDX1818Š@�”˜When a program is executed, it receives information about the context in which it was invoked in two ways. The first mechanism uses the Bargv@ and Bargc@ arguments to its Hmain@ function, and is discussed in section ‰ŠP�”›Program Arguments@�”˜. The second mechanism uses Benvironment variables@ and is discussed in this section.
The Bargv@ mechanism is typically used to pass command-line arguments specific to the particular program being invoked. The environment, on the other hand, keeps track of information that is shared by many programs, changes infrequently, and that is less frequently used.
The environment variables discussed in this section are the same environment variables that you set using assignments and the Hexport@ command in the shell. Programs executed from the shell inherit all of the environment variables from the shell.
‰IDX1819Š@�”˜Standard environment variables are used for information about the user's home directory, terminal type, current locale, and so on; you can define additional variables for other purposes. The set of all environment variables that have values is collectively known as the Benvironment@.
Names of environment variables are case-sensitive and must not contain the character H`='@. System-defined environment variables are invariably uppercase.
The values of environment variables can be anything that can be represented as a string. A value must not contain an embedded null character, since this is assumed to terminate the string.
ˆ‰SEC399ŠT�”›Environment Access

‰IDX1820Š‰IDX1821Š
@�”˜The value of an environment variable can be accessed with the Hgetenv@ function. This is declared in the header file H`stdlib.h'@. ‰IDX1822Š

A�”˜Function:@ char * Dgetenv@ B(const char *Bname@)
Â‰IDX1823Š@�”˜This function returns a string that is the value of the environment variable Bname@. You must not modify this string. In some non-Unix systems not using the GNU library, it might be overwritten by subsequent calls to Hgetenv@ (but not by any other library function). If the environment variable Bname@ is not defined, the value is a null pointer.À

AFunction:@ int Dputenv@ B(const char *Bstring@)
Â‰IDX1824Š@�”˜The Hputenv@ function adds or removes definitions from the environment. If the Bstring@ is of the form H`JnameH=JvalueH'@, the definition is added to the environment. Otherwise, the Bstring@ is interpreted as the name of an environment variable, and any definition for this variable in the environment is removed.
The GNU library provides this function for compatibility with SVID; it may not be available in other systems.À

You can deal directly with the underlying representation of environment objects to add more variables to the environment (for example, to communicate with another program you are about to execute; see section ‰ŠP�”›Executing a File@�”˜).

AVariable:@ char ** Denviron
Â‰IDX1825Š@�”˜The environment is represented as an array of strings. Each string is of the format H`JnameH=JvalueH'@. The order in which strings appear in the environment is not significant, but the same Bname@ must not appear more than once. The last element of the array is a null pointer.
This variable is declared in the header file H`unistd.h'@.
If you just want to get the value of an environment variable, use Hgetenv@.À

Unix systems, and the GNU system, pass the initial value of Henviron@ as the third argument to Hmain@. See section ‰ŠP�”›Program Arguments@�”˜.
ˆ‰SEC400ŠT�”›Standard Environment Variables

‰IDX1826Š
@�”˜These environment variables have standard meanings. This doesn't mean that they are always present in the environment; but if these variables Bare@ present, they have these meanings. You shouldn't try to use these environment variable names for some other purpose.
HHOME
Â‰IDX1827Š‰IDX1828Š@�”˜This is a string representing the user's Bhome directory@, or initial default working directory. The user can set HHOME@ to any value. If you need to make sure to obtain the proper home directory for a particular user, you should not use HHOME@; instead, look up the user's name in the user database (see section ‰ŠP�”›User Database@�”˜). For most purposes, it is better to use HHOME@, precisely because this lets the user specify the value.
ÀHLOGNAME
Â‰IDX1829Š@�”˜This is the name that the user used to log in. Since the value in the environment can be tweaked arbitrarily, this is not a reliable way to identify the user who is running a process; a function like Hgetlogin@ (see section ‰ŠP�”›Identifying Who Logged In@�”˜) is better for that purpose. For most purposes, it is better to use HLOGNAME@, precisely because this lets the user specify the value.
ÀHPATH
Â‰IDX1830Š@�”˜A Bpath@ is a sequence of directory names which is used for searching for a file. The variable HPATH@ holds a path used for searching for programs to be run. The Hexeclp@ and Hexecvp@ functions (see section ‰ŠP�”›Executing a File@�”˜) use this environment variable, as do many shells and other utilities which are implemented in terms of those functions. The syntax of a path is a sequence of directory names separated by colons. An empty string instead of a directory name stands for the current directory (see section ‰ŠP�”›Working Directory@�”˜). A typical value for this environment variable might be a string like: :/bin:/etc:/usr/bin:/usr/new/X11:/usr/new:/usr/local/bin This means that if the user tries to execute a program named Hfoo@, the system will look for files named H`foo'@, H`/bin/foo'@, H`/etc/foo'@, and so on. The first of these files that exists is the one that is executed.
ÀHTERM
Â‰IDX1831Š@�”˜This specifies the kind of terminal that is receiving program output. Some programs can make use of this information to take advantage of special escape sequences or terminal modes supported by particular kinds of terminals. Many programs which use the termcap library (see section `Finding a Terminal Description' in BThe Termcap Library Manual@) use the HTERM@ environment variable, for example.
ÀHTZ
Â‰IDX1832Š@�”˜This specifies the time zone. See section ‰ŠP�”›Specifying the Time Zone with XTZ@�”˜, for information about the format of this string and how it is used.
ÀHLANG
Â‰IDX1833Š@�”˜This specifies the default locale to use for attribute categories where neither HLC_ALL@ nor the specific environment variable for that category is set. See section ‰ŠP�”›Locales and Internationalization@�”˜, for more information about locales.
ÀHLC_COLLATE
Â‰IDX1834Š@�”˜This specifies what locale to use for string sorting.
ÀHLC_CTYPE
Â‰IDX1835Š@�”˜This specifies what locale to use for character sets and character classification.
ÀHLC_MONETARY
Â‰IDX1836Š@�”˜This specifies what locale to use for formatting monetary values.
ÀHLC_NUMERIC
Â‰IDX1837Š@�”˜This specifies what locale to use for formatting numbers.
ÀHLC_TIME
Â‰IDX1838Š@�”˜This specifies what locale to use for formatting date/time values.
ÀH_POSIX_OPTION_ORDER
Â‰IDX1839Š@�”˜If this environment variable is defined, it suppresses the usual reordering of command line arguments by Hgetopt@. See section ‰ŠP�”›Program Argument Syntax Conventions@�”˜. À

ˆ‰SEC401Št�”›Program Termination

‰IDX1840Š‰IDX1841Š
‰IDX1842Š@�”˜The usual way for a program to terminate is simply for its Hmain@ function to return. The Bexit status value@ returned from the Hmain@ function is used to report information back to the process's parent process or shell.
A program can also terminate normally by calling the Hexit@ function.
In addition, programs can be terminated by signals; this is discussed in more detail in section ‰ŠP�”›Signal Handling@�”˜. The Habort@ function causes a signal that kills the program.
ˆ‰SEC402ŠT�”›Normal Termination

@�”˜A process terminates normally when the program calls Hexit@. Returning from Hmain@ is equivalent to calling Hexit@, and the value that Hmain@ returns is used as the argument to Hexit@.

AFunction:@ void Dexit@ B(int Bstatus@)
Â‰IDX1843Š@�”˜The Hexit@ function terminates the process with status Bstatus@. This function does not return.À

Normal termination causes the following actions: þÂ
1. Functions that were registered with the Hatexit@ or Hon_exit@ functions are called in the reverse order of their registration. This mechanism allows your application to specify its own "cleanup" actions to be performed at program termination. Typically, this is used to do things like saving program state information in a file, or unlocking locks in shared data bases.
2. All open streams are closed, writing out any buffered output data. See section ‰ŠP�”›Closing Streams@�”˜. In addition, temporary files opened with the Htmpfile@ function are removed; see section ‰ŠP�”›Temporary Files@�”˜.
3. H_exit@ is called, terminating the program. See section ‰ŠP�”›Termination Internals@�”˜.Àð
ˆ‰SEC403ŠT�”›Exit Status

‰IDX1844Š
@�”˜When a program exits, it can return to the parent process a small amount of information about the cause of termination, using the Bexit status@. This is a value between 0 and 255 that the exiting process passes as an argument to Hexit@.
Normally you should use the exit status to report very broad information about success or failure. You can't provide a lot of detail about the reasons for the failure, and most parent processes would not want much detail anyway.
There are conventions for what sorts of status values certain programs should return. The most common convention is simply 0 for success and 1 for failure. Programs that perform comparison use a different convention: they use status 1 to indicate a mismatch, and status 2 to indicate an inability to compare. Your program should follow an existing convention if an existing convention makes sense for it.
A general convention reserves status values 128 and up for special purposes. In particular, the value 128 is used to indicate failure to execute another program in a subprocess. This convention is not universally obeyed, but it is a good idea to follow it in your programs.
DWarning:@ Don't try to use the number of errors as the exit status. This is actually not very useful; a parent process would generally not care how many errors occurred. Worse than that, it does not work, because the status value is truncated to eight bits. Thus, if the program tried to report 256 errors, the parent would receive a report of 0 errors--that is, success.
For the same reason, it does not work to use the value of Herrno@ as the exit status--these can exceed 255.
DPortability note:@ Some non-POSIX systems use different conventions for exit status values. For greater portability, you can use the macros HEXIT_SUCCESS@ and HEXIT_FAILURE@ for the conventional status value for success and failure, respectively. They are declared in the file H`stdlib.h'@. ‰IDX1845Š

A�”˜Macro:@ int DEXIT_SUCCESS
Â‰IDX1846Š@�”˜This macro can be used with the Hexit@ function to indicate successful program completion.
On POSIX systems, the value of this macro is H0@. On other systems, the value might be some other (possibly non-constant) integer expression.À

AMacro:@ int DEXIT_FAILURE
Â‰IDX1847Š@�”˜This macro can be used with the Hexit@ function to indicate unsuccessful program completion in a general sense.
On POSIX systems, the value of this macro is H1@. On other systems, the value might be some other (possibly non-constant) integer expression. Other nonzero status values also indicate failures. Certain programs use different nonzero status values to indicate particular kinds of "non-success". For example, Hdiff@ uses status value H1@ to mean that the files are different, and H2@ or more to mean that there was difficulty in opening the files.À

ˆ‰SEC404ŠT�”›Cleanups on Exit

@�”˜Your program can arrange to run its own cleanup functions if normal termination happens. If you are writing a library for use in various application programs, then it is unreliable to insist that all applications call the library's cleanup functions explicitly before exiting. It is much more robust to make the cleanup invisible to the application, by setting up a cleanup function in the library itself using Hatexit@ or Hon_exit@.

AFunction:@ int Datexit@ B(void (*Bfunction@) (void))
Â‰IDX1848Š@�”˜The Hatexit@ function registers the function Bfunction@ to be called at normal program termination. The Bfunction@ is called with no arguments.
The return value from Hatexit@ is zero on success and nonzero if the function cannot be registered.À

AFunction:@ int Don_exit@ B(void (*Bfunction@)(int Bstatus@, void *Barg@), void *Barg@)
Â‰IDX1849Š@�”˜This function is a somewhat more powerful variant of Hatexit@. It accepts two arguments, a function Bfunction@ and an arbitrary pointer Barg@. At normal program termination, the Bfunction@ is called with two arguments: the Bstatus@ value passed to Hexit@, and the Barg@.
This function is included in the GNU C library only for compatibility for SunOS, and may not be supported by other implementations.À

Here's a trivial program that illustrates the use of Hexit@ and Hatexit@: #include <stdio.h>
#include <stdlib.h>

void
bye (void)
{
puts ("Goodbye, cruel world....");
}

int
main (void)
{
atexit (bye);
exit (EXIT_SUCCESS);
}
When this program is executed, it just prints the message and exits.
ˆ‰SEC405ŠT�”›Aborting a Program

‰IDX1850Š
@�”˜You can abort your program using the Habort@ function. The prototype for this function is in H`stdlib.h'@. ‰IDX1851Š

A�”˜Function:@ void Dabort@ B(void)
Â‰IDX1852Š@�”˜The Habort@ function causes abnormal program termination. This does not execute cleanup functions registered with Hatexit@ or Hon_exit@.
This function actually terminates the process by raising a HSIGABRT@ signal, and your program can include a handler to intercept this signal; see section ‰ŠP�”›Signal Handling@�”˜.À

DFuture Change Warning:@ Proposed Federal censorship regulations may prohibit us from giving you information about the possibility of calling this function. We would be required to say that this is not an acceptable way of terminating a program.
ˆ‰SEC406ŠT�”›Termination Internals

@�”˜The H_exit@ function is the primitive used for process termination by Hexit@. It is declared in the header file H`unistd.h'@. ‰IDX1853Š

A�”˜Function:@ void D_exit@ B(int Bstatus@)
Â‰IDX1854Š@�”˜The H_exit@ function is the primitive for causing a process to terminate with status Bstatus@. Calling this function does not execute cleanup functions registered with Hatexit@ or Hon_exit@.À

When a process terminates for any reason--either by an explicit termination call, or termination as a result of a signal--the following things happen: þÂ
• All open file descriptors in the process are closed. See section ‰ŠP�”›Low-Level Input/Output@�”˜. Note that streams are not flushed automatically when the process terminates; See section ‰ŠP�”›Input/Output on Streams@�”˜.
• The low-order 8 bits of the return status code are saved to be reported back to the parent process via Hwait@ or Hwaitpid@; see section ‰ŠP�”›Process Completion@�”˜.
• Any child processes of the process being terminated are assigned a new parent process. (On most systems, including GNU, this is the Hinit@ process, with process ID 1.)
• A HSIGCHLD@ signal is sent to the parent process.
• If the process is a session leader that has a controlling terminal, then a HSIGHUP@ signal is sent to each process in the foreground job, and the controlling terminal is disassociated from that session. See section ‰ŠP�”›Job Control@�”˜.
• If termination of a process causes a process group to become orphaned, and any member of that process group is stopped, then a HSIGHUP@ signal and a HSIGCONT@ signal are sent to each process in the group. See section ‰ŠP�”›Job Control@�”˜.Àð
Œ
Go to the ‰ŠP�”›first@�”˜, ‰ŠP�”›previous@�”˜, ‰ŠP�”›next@�”˜, ‰ŠP�”›last@�”˜ section, ‰ŠP�”›table of contents@�”˜.