C atexit() Function Tutorial

In this section, we will learn what the atexit() function is and how it works in C.

atexit() Function in C

When a program terminated via either a call to the exit() function or upon the return from the main() function, we can define one or more functions to be run at that time with the help of `atexit()` function.

The use of atexit() function is mainly useful when we have multiple external connection to our program and want to terminate this connection before actually finishing the program itself.

Be aware that the prototype of the `atexit()` function is in `stdlib.h` header file and so we need to include the file in order to use the function.

atexit() Function Syntax

Here’s the prototype of the function:

int atexit(void (*func)(void))

atexit() Function Parameters

The `atexit()` takes the address of a function and, when the program is about to terminate, will call that function to run it.

Note: the name of a function is its address.

atexit() Function Return Value

The return value of this function is 0 if the target function registered successfully and non-zero otherwise.

Example: using atexit() function in C

#include <stdio.h>
#include <stdlib.h>
void messageOne();
void messageTwo();
int main() {

    atexit(messageTwo);
    atexit(messageOne);
    printf("End of the call to the main-function\n");
    return 0;
}
void messageOne(){
    printf("Terminating the program\n");
}
void messageTwo(){
    printf("The program is about to terminate\n");
}

Output:

End of the call to the main-function

Terminating the program

The program is about to terminate

As you can see from this example, within the body of the `main()` function, we registered two functions to be run when the program is about to terminate.

The order of executions of functions that are registered with `atexit()` function is the same order as they were registered. So in this example, the first function to be run at termination time is `messageTwo()` and the second one is `messageOne()` function.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies