tags:

views:

253

answers:

3

Is it possible to call an extra function when main() exits in C?

Thanks!

+20  A: 

You can register functions to run after main exits using the atexit function.

MSDN has a nice succinct example of how this is done. Basically, the functions registered with atexit are executed in reverse order of when they were registered.

James McNellis
actually nice answer :)
SjB
Occasionally a blind squirrel finds a nut...
James McNellis
just what i needed, thank you!
edarroyo
atexit() is a frequent source of platform-specific weirdness and unpredictable crashes. For example the OpenBSD manpage advises not to use it. I was looking for some articles I read circa 2003 on the subject, but was unable to find them...
asveikau
@asveikau: OpenBSD advises not to use it because of races at exit-time. Is it the case that a single-threaded OpenBSD program suffers from weirdness and unpredictable crashes on exit if it has used atexit() naively? If so that's a worry, but I don't see why in principle a non-compliant implementation of the function on one platform should mean you ought not to use it on other platforms. If you write multi-threaded code, then of course you have to look to your platform's treatment of "hidden" global data like the atexit list...
Steve Jessop
Really,nice examples !!
nthrgeek
@Steve I wish I could find those old articles on the subject so I could refresh my memory on their particular reasoning. I seem to recall it applied to other systems as well. FWIW, I've experienced a few bugs firsthand because atexit() was called without realizing that the handlers persist on a fork(), or exit() was called from within a signal handler or while a lock is held, or if the handler comes from a shared library that gets unloaded. Similar to signals, you really should be careful where your handler comes from and what it does.
asveikau
I guess you can be careless about how you call exit, or you can be careless about how you call atexit, but not both. Most programmers prefer the former.
Steve Jessop
+7  A: 

Try the atexit() function:

void myfunc() {
    /* Called when the program ends */
}

int main( int arc, char *argv[] ) {
    atexit( myfunc );
    ...
    return 0;
}
Graeme Perrow
+2  A: 

Great question and answers. Just a side note. Abuse of a similar feature in Delphi libraries led to applications which are annoyingly slow on close.

RocketSurgeon