Inside my atexit() registered function I would like to get the exit status (either the argument to exit(3) or what main() returned with).
Is there any portable way of doing this? Is there any GNU libc specific way of doing it such as a global holding that value I can reference?
The function pointed by atexit() is automatically called without arguments when the program terminates normally. In case more than one function has been specified by different calls to the atexit() function, all are executed in the order of a stack (i.e. the last function specified is the first to be executed at exit).
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.
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.
Here's a hack:
// hack.c
int last_exit;
// hack.h
extern int last_exit;
#define exit(x) (exit)(last_exit = (x))
Won't work for return
, but, hey, it's portable!
On a more maintainer-friendly note, you may want to consider writing some form of wrapper to do something similar to this for you. Hacking around how GCC implements exit()
sounds like a maintenance nightmare. Better to write a few helper functions that exit for you, and maybe even mask them with macros if you're into that kind of thing. With a macro you might even be able to replace return
calls, if you always call return
with parenthesis. Though this sounds like even more of a maintenance nightmare.
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