Home » Programming Languages » C library API atexit for calling certain function at end of program execution / process termination

C library API atexit for calling certain function at end of program execution / process termination

atexit – register a function to be called at normal process termination

The atexit() function registers the given function to be called at normal process termination, either via exit(3) or via return from the program’s main(). Functions so registered are called in the reverse order of their registration; no arguments are passed. The same function may be registered multiple times: it is called once for each registration.

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

void bye(void) {
        printf("Function called after execution of atexit !\n");
}

int addnum(int a, int b) {
        return a+b;
}

int main(void) {
        int i, sum;

        printf("Normal start of program execution\n");

        printf("Registering \"bye\" function using atexit c library API");
        i = atexit(bye);
        if (i != 0) {
                fprintf(stderr, "cannot set exit function\n");
                exit(EXIT_FAILURE);
        }

        printf("Calling two numbers adding function\n");
        sum = addnum(10,5);
        printf("Two numbers added using addnum function after registering atexit: sum = %d\n", sum);

        printf("Normal end of program execution\n");
        exit(EXIT_SUCCESS);
}
$ gcc -o atexit_example atexit_example.c
$ ./atexit_example
Normal start of program execution
Registering "bye" function using atexit c library APICalling two numbers adding function
Two numbers added using addnum function after registering atexit: sum = 15
Normal end of program execution
Function called after execution of atexit !

As you can see above, The message printed from “bye” function has got executed at very last of the program execution even though we registered this function using “atexit” at the start of program.

This atexit api is useful when you need to make sure that certain cleanup code or some task needs to be executed only at the end of program.


Subscribe our Rurban Life YouTube Channel.. "Rural Life, Urban LifeStyle"

Leave a Comment