ptg10805159
Section 7.3 Process Termination 199
Historically,theexitfunction has always performed a clean shutdown of the
standardI/O library: thefclosefunction is called for all open streams. Recall from
Section 5.5 that this causes all buffered output data to be flushed (written to the file).
All three exit functions expect a single integer argument, which we call theexit
status.Most UNIX System shells provide a way to examine the exit status of a process.
If (a) any of these functions is called without an exit status, (b)maindoes areturn
without a return value, or (c) themainfunction is not declared to return an integer,the
exit status of the process is undefined. However, if the return type ofmainis an integer
andmain‘‘falls offthe end’’(an implicit return), the exit status of the process is 0.
This behavior is new with the 1999 version of the ISO C standard. Historically,the exit status
was undefined if the end of themainfunction was reached without an explicitreturn
statement or a call to theexitfunction.
Returning an integer value from themainfunction is equivalent to callingexit
with the same value. Thus
exit(0);
is the same as
return(0);
from themainfunction.
Example
The program in Figure7.1 is the classic ‘‘hello, world’’example.
#include <stdio.h>
main()
{
printf("hello, world\n");
}
Figure 7.1 Classic C program
When we compile and run the program in Figure7.1, we see that the exit code is
random. If we compile the same program on different systems, we arelikely to get
different exit codes, depending on the contents of the stack and register contents at the
time that themainfunction returns:
$gcc hello.c
$./a.out
hello, world
$echo $? print the exit status
13