...
- Flushes unwritten buffered data.
- Closes all open files.
- Removes temporary files.
- Returns an integer exit status to the operating system.
The C standard atexit()
function to customize exit()
to perform additional actions at program termination.
For example, calling:
Code Block | ||
---|---|---|
| ||
atexit(turn_gizmo_off); |
registers the turn_gizmo_off()
function so that a subsequent call to exit()
will invoke turn_gizmo_off()
as it terminates the program. According to C99, atexit()
can register up to 32 functions.
atexit()
is only called by exit()
or upon normal completion of main()
.
_Exit()
A less polite more abrupt function, _Exit()
also takes one argument and never returns. The standard specifies that _Exit()
also closes open file descriptors, but does not specify if _Exit()
flushes file buffers or deletes temporary files. Functions registered by atexit()
are not executed.
Code Block | ||
---|---|---|
| ||
#include <stdlib.h> /* ... */ if (/* something really bad happened */) { _Exit(EXIT_FAILURE); } |
The _exit()
function is a synonym for _Exit()
.
abort()
The quickest and most abrupt way to terminate a program, abort()
takes no parameterarguments, and always signifies abnormal termination to the operating system.
Code Block | ||
---|---|---|
| ||
{code:bgColor=#ccccff}
#include <stdlib.h>
/* ... */
if (/* something really bad happened */) {
abort();
}
|
The abort()
function causes abnormal program termination to occur, unless the signal SIGABRT
is being caught and the signal handler does not return.
Whether open streams with unwritten buffered data are flushed, open streams are closed, or temporary files are removed is implementation-defined. Functions registered by atexit()
are not executed.
Summary
Function | Closes file descriptors | Flushes buffers | Deletees temporary files | Calls |
---|---|---|---|---|
abort() | unspecified | unspecified | unspecified | no |
_Exit(status) | yes | unspecified | unspecified | no |
exit(status) | yes | yes | yes | yes |
atexit()
You can use the Standard C atexit() function to customize exit() to perform additional actions at program termination.
For example, calling:
Code Block | ||
---|---|---|
| ||
atexit(turn_gizmo_off);
|
"registers" the turn_gizmo_off()
function so that a subsequent call to exit()
will invoke turn_gizmo_off();
as it terminates the program. The C standard says that atexit()
should let you register up to 32 functions.
...
Non-Compliant Code Example
...