开发者

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

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

开发者_如何学C 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?


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.


Exit handler allows a library to do shutdown cleanup (thus of global data structure) without the main program being aware of that need. Two examples of things I've done in an exit handler:

  • restoring tty flags

  • closing correctly a network connection so that the peer hadn't to wait a time out

Your probably can think of other use.


The most obvious problem that an atexit handler solves, is tidy up for global objects. This is a C feature and of course C doesn't have automatic deallocation like C++. If you have access to the implementation of main you can write your own such code, but otherwise atexit can be helpful.


Read this blog post on Start and Termination in C++:

When a program is terminating it needs to do some finishing touches like saving data to a file that will be used in the next session. In this light each program has a particular set of things to do depending on the purpose of the program (when closing). Any of such things done is done by one of the functions whose pointer would be argument to the atexit function.

The purpose of the atexit function is to register (record in memory) the functions for these finishing touches. When the atexit function executes using any of the pointers to these functions as argument the pointed function is registered. This has to be done before the C++ program reaches its termination phase.

Read more: http://www.bukisa.com/articles/356786_start-and-termination-in-c#ixzz1WdWVl4TF

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜