Search code examples
cexitatexit

How can I use atexit() function to cleanup function call?


I am using atexit() function inside my code to cleanup function call, but it's not working.

#include<stdio.h>
void ftn(void)
{
    printf(" Function called --> exit\n");
    return;
}
int main(void)
{
    int x = 0;
    atexit(ftn);
    for(;x<0xffffff;x++);
    _exit(0);
}

Any help regarding this will be appreciated.


Solution

  • This behavior of atexit() function is due to the use of function _exit(). This function does not call the clean-up functions like atexit() etc. If atexit() is required to be called then exit() or ‘return’ should be used instead of _exit().

    As:

    #include<stdio.h>
    void ftn(void)
    {
        printf(" Function called --> exit\n");
        return;
    }
    int main(void)
    {
        int x = 0;
        atexit(ftn);
        for(;x<0xffffff;x++);
        exit(0);
    }