Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is a function registered with atexit() called

I want to know if functions registered with atexit() are called before or after global variables are destroyed. Is this specified by the standard or implementation defined?

like image 614
Mircea Ispas Avatar asked Nov 27 '12 14:11

Mircea Ispas


People also ask

What is the use of atexit () function?

The atexit() function registers the given function to be called at normal process termination, either via exit(3) or via return from the program's main(). Functions so registered are called in the reverse order of their registration; no arguments are passed.

What is Atexit register?

atexit is a module in python which contains two functions register() and unregister(). The main role of this module is to perform clean up upon interpreter termination. Functions that are registered are automatically executed upon interpreter termination.

What is atexit function in C?

In the C Programming Language, the atexit function registers a function as a termination function which is called if the program terminates normally. When calling the atexit function more than once, the last function to be registered is the first function that will be called when the program is terminated normally.

Which standard library function can be used to call clean up tasks?

The atexit subroutine registers functions called at normal process termination for cleanup processing.


1 Answers

It is well-defined, and depends on whether the object in question was constructed before or after the function got registered using atexit():

3.6.3 Termination

3. If the completion of the initialization of an object with static storage duration is sequenced before a call to std::atexit (see <cstdlib>, 18.5), the call to the function passed to std::atexit is sequenced before the call to the destructor for the object. If a call to std::atexit is sequenced before the completion of the initialization of an object with static storage duration, the call to the destructor for the object is sequenced before the call to the function passed to std::atexit. If a call to std::atexit is sequenced before another call to std::atexit, the call to the function passed to the second std::atexit call is sequenced before the call to the function passed to the first std::atexit call.

My layman's interpretation of the above is that stuff that got constructed before you called atexit(handler) gets destroyed after handler() is called, and vice versa. I am sure there are subtleties, but this seems to be the basic principle.

like image 51
NPE Avatar answered Sep 22 '22 07:09

NPE