Versions Compared

Key

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

...

In this example the function 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 <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().

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);
}

Compliant Code

To have functionality where the program can quit from within a function registered by at_exit() it is necessary to use a function used for abnormal termination such as _Exit() or abort().

_Exit() and abort() will both immediately halt program execution, and may be used within functions registered by atexit().

Wiki Markup
According to C99, \[[ISO/IEC 9899-1999:TC2|AA. C References#ISO/IEC 9899-1999TC2]\]:
\\
_Exit() a c99 defined function is described as follows: 

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.

...

The call to _Exit() will immediately terminate the program and no undefined behavior will happen like in the non compliant example.

Risk Assessment

Multiple calls to exit in code are likely to be rare but if exist can are unlikely, and at worst will only cause denial of service and attacks or abnormal program termination.

...