Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the exit status from inside an function registered with atexit()

Tags:

c

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?

like image 399
Sean A.O. Harney Avatar asked Feb 04 '10 02:02

Sean A.O. Harney


People also ask

What is the use of atexit () function?

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).

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.

How does Atexit work 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.


1 Answers

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.

like image 70
Chris Lutz Avatar answered Oct 11 '22 17:10

Chris Lutz