Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What would you use an exit handler for? [duplicate]

Tags:

c

unix

Possible Duplicate:
what is the purpose of atexit function?

In UNIX at least: I'm aware that C/C++ can register a number of functions to be called at the exit of main - exit handlers. Thee functions to be called can be registered, in reverse order, using:

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

I'm having trouble determining how this would be useful though. The functions are void/void and global, so they are unlikely to have access to many variables around the program unless the variables are also globals. Can someone let me know the kinds of things you would do with exit handlers?

Also, do exit handlers work the same way on non-UNIX platforms since they're part of an ANSI C specification?

like image 811
John Humphreys Avatar asked Aug 31 '11 19:08

John Humphreys


People also ask

What is exit handler?

Exit handler allows a library to do shutdown cleanup (thus of global data structure) without the main program being aware of that need.

What is exit handler in SQL?

EXIT. Specifies that after SQL-procedure-statement completes, execution continues at the end of the compound statement that contains the handler. Example: CONTINUE handler: This handler sets flag at_end when no more rows satisfy a query.

What are the types of handlers in MySQL?

A handler can be specific or general. A specific handler is for a MySQL error code, SQLSTATE value, or condition name. A general handler is for a condition in the SQLWARNING , SQLEXCEPTION , or NOT FOUND class. Condition specificity is related to condition precedence, as described later.

What is use of continue handler in MySQL?

CONTINUE : Execution of the current program continues. EXIT : Execution terminates for the BEGIN ... END compound statement in which the handler is declared. This is true even if the condition occurs in an inner block.


1 Answers

You can perform cleanup for global objects in a atexit handler:

static my_type *my_object;

static void my_object_release() { free(my_object); }

my_type *get_my_object_instance() 
{
    if (!my_object)
    {
        my_object = malloc(sizeof(my_type));
        ...
        atexit(my_object_release);
    }

    return my_object;
}

If you want to be able to close over some variables in an atexit-like handler, you can devise your own data structure containing cleanup function/parameter pairs, and register a single atexit handler calling all the said functions with their corresponding arguments.

like image 184
Alexandre C. Avatar answered Oct 05 '22 14:10

Alexandre C.