Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

The C99 exit() function is used for normal program termination. If more than one call Nested calls to exit() is executed by a program, the behavior is undefined. 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 as a result of being registered with atexit() has an exit() call in it there is undefined behavior result in undefined behavior. This most frequently occurs when registering functions with atexit().

Non-Compliant Code Example

In this example the function So that it might perform cleanup upon program termination, exit1() is registered by atexit() so upon program termination exit1() is called and certain cleanup and maintenance functions can occur. If some failure case <expr> evaluates as true though the program attempts to fully exit before the cleanup code can be processed. In these cases where <expr> evaluates to true, exit() will be called twice and the behavior is undefined. Some compilers will simply ignore the exit() call as it in is a function registered by atexit()a second time, resulting in undefined behavior.

Code Block
bgColor#FFcccc
#include <stdio.h>
#include <stdlib.h>

void exit1(void) {
   if(<expr>) {
      /* ...cleanup code... */
      exit(0);
   }
}

int main (void) {
    atexit(exit1);
    /* ...program code... */
    exit(0);
}

...

Wiki Markup
According to C99, \[[ISO/IEC 9899-1999:TC2|AA. C References#ISO/IEC 9899-1999TC2]\]:
\\

The function _exit terminates the calling process "immediately". Any open file descriptors belonging to the process are closed; any children of the process are inherited by process 1, init, and the process's parent is sent a SIGCHLD signal. The value status is returned to the parent process as the process's exit status, and can be collected using one of the wait family of calls. The function _Exit is equivalent to _exit _Exit function causes normal program termination to occur and control to be
returned to the host environment. No functions registered by the atexit function or
signal handlers registered by the signal function are called. The status returned to the host environment is determined in the same way as for the exit function.
Whether open streams with unwritten buffered data are flushed, open streams are closed,
or temporary files are removed is implementation-defined. The _Exit function cannot return to its caller.

Code Block
bgColor#ccccFF
#include <stdio.h>
#include <stdlib.h>

void exit1(void) {
   if(<expr>) {
      /* ...cleanup code... */
      _Exit(0);
   }
}

int main (void) {
    atexit(exit1);
    /* ...program code... */
    exit(0);
}

...