10

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

Thanks!

4 Answers 4

23

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.

Sign up to request clarification or add additional context in comments.

5 Comments

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: 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 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.
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: Even without atexit, being careless about how you call exit is dangerous. It's not async-signal-safe, and since it flushes all open files, it's almost sure to give you problems if you break the rules about calling it.
9

Try the atexit() function:

void myfunc() { /* Called when the program ends */ } int main( int arc, char *argv[] ) { atexit( myfunc ); ... return 0; } 

Comments

2

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.

Comments

1

While atexit() is the standard for registering a function to run at process termination, GCC provides a destructor function attribute* that causes a function to be called automatically when main() has completed or exit() has been called.

void __attribute__ ((destructor)) my_fini(void); 

* GCC specific

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.