C Programming/stdlib.h/atexit

From Wikibooks, open books for an open world
Jump to: navigation, search

atexit (at exit) is a function that is in the C Programming Language to register the given function to be executed at normal process termination, either via exit or via return from the program's main function.

The atexit function takes, as argument, the reference of the function to be registered for call back. Functions so registered are called in the reverse order of their registration; no arguments are passed.

POSIX Usage[edit]

The atexit function is standardized by the POSIX specification.

The prototype of the function is as below:

int atexit(void (*function)(void));

The function returns zero (0) if it completed execution successfully. Non-zero return values signify an error.

POSIX requires that an implementation of atexit allow at least ATEXIT_MAX (32) such functions to be registered.


The following example demonstrates the use of the atexit function.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void end(void) {
        printf("[ DONE ]\n");
int main(){
        long ret;
        ret = sysconf(_SC_ATEXIT_MAX);
        printf("ATEXIT_MAX = %ld\n", ret);
        if( atexit(end) != 0 ) {
                perror("Unable to set exit function\n");
                return EXIT_FAILURE;
        printf( "About to quit... " );
        return EXIT_SUCCESS;


ISO/IEC 9899:1999 specification. p. 315, § http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf. 

External links[edit]