void The C99 exit(
int status)
The exit function is used for normal program termination to occur. If more than one call to exit()
is executed by a program, the behavior is undefined. This type of situation typically only happens This may occur when functions are registered with atexit()
, a function that causes the functions registered to it to be called with when the program exits. If a function called due to as a result of being registered with atexit()
has an exit()
call in it there is undefined behavior.
...
In this code as the main function exits two functions registered with atexit()
are called. Given the define statement exitearly=1 the program calls exit within the first function called in the atexit() cycle. The behavior that follows is undefined: some implementations will ignore the second call to exit and just continue calling the atexit functions in the appropriate order. Other implementations will enter an infinite loop with the atexit functions being called repeatedly.
Code Block | ||
---|---|---|
| ||
#include <stdio.h> #include <stdlib.h> #define exitearly 1 void exit1 (void) { printfputs("Exit second.\n"); } void exit2 (void) { printfputs("Exit first.\n"); if (exitearly) { exit(1); } } int main (void) { atexit (exit1); atexit (exit2); printfputs("In main\n"); exit(1); return 0; } |
...
To have functionality where the program can quit from within a function registered by at_exit() one has it is necessary to use a function used for abnormal termination such as _exit() or abort().
...
Code Block | ||
---|---|---|
| ||
#include <stdio.h>
#include <stdlib.h>
#define exitearly 1
void exit1 (void)
{
printf("Exit second.\n");
}
void exit2 (void)
{
printf("Exit first.\n");
if(exitearly)
{
_exit(1);
}
}
int main ()
{
atexit (exit1);
atexit (exit2);
printf("In main\n");
exit(1);
return 0;
}
|
...