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?
Exit handler allows a library to do shutdown cleanup (thus of global data structure) without the main program being aware of that need.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With