atexit(): Execute code just before terminating

Tags: / c /

About the ~atexit()~ function in C that can be used to run code.

From my old blog.


atexit() is a function which can be used to call functions having code that needs to be executed just before terminating the program normally.

For this to work, the functions which must be executed just before termination must first be 'registered' with the atexit() function. It’s like informing atexit() that a certain function needs to be executed before termination.

Eg: To register a function fn1(), do

atexit(fn1);

Functions registered with atexit() are called in the reverse order of the order in which they were registered.

ie, if the function fn1(), fn2(), fn3() were registered like

atexit(fn1);
atexit(fn2);
atexit(fn3);
atexit(fn1);

The order of execution of these functions would be fn1(), fn3(), fn2(), fn1().

For example, the following program

#include<stdio.h>
#include<stdlib.h>

void call_me_before(void)
{
    printf("Call me before...\n");
}

void you_terminate(void)
{
    printf("... you terminate.\n");
}

int main()
{
    atexit(you_terminate);
    atexit(call_me_before);
}

would give

Call me before...
... you terminate.

We can even register the same function multiple times to make that function run more than once.

The functions that need to be executed using atexit() must have void as their return type and can’t be taking arguments.

This is why the argument of atexit() is a pointer to function of return type void taking no arguments.

The signature of atexit() is:

void (*function)(void);

In POSIX-compliant systems, at least 32 functions can be registered in this way. ¹

This is as per the value of ATEXIT_MAX defined inside limits.h header file. It denotes the maximum number of functions that may be registered with the atexit() function. ³

It may not be executed if some error occurred in the program which causes it to terminate prematurely like a segmentation fault.

Return value: 0 when successful. Otherwise a non-zero value.

References