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.

Android Android Commands Android Java Applications Application Libraries Application Stack / User Interface Bash / Shell Scripts Commands and Packages Compilation Content Management System - CMS Core Kernel C Programs Development & Build Development Environment Setup Errors & Failures Flutter git Go Language Programs Hardware Platforms HTML JAVA Programs Kernel & Device Drivers Linux, OS Concepts and Networking Linux Device Drivers Linux Host, Ubuntu, SysAdmin Linux Kernel Linux Networking Middleware Libraries, HAL Monetization / Google AdSense NDK / Middleware / HAL OS Concepts PHP Programming Languages RaspberryPi Scripting and Automation Search Engine Optimisation ( SEO ) Social Media Socurce Code Management ( SCM ) System Administration, Security Testing and Debugging Uncategorized User Interface Userspace Utilities Web design and development Wordpress Yocto / Bitbake / Openembedded

Leave a Reply / Ask Question