tags:

views:

52

answers:

1

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?

+1  A: 

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.

Chris Lutz
Thanks. Yes setting my own global before calling exit() and using that in my registered func seems like the best idea.
Sean A.O. Harney
Remember the parenthesis around `exit` in the macro - they make sure that the macro won't try to call itself, but allow the macro to call a function of the same name. I only recently learned that trick, but it allows you to avoid making your hack clearly obvious with something like `#define EXIT(x) exit(last_exit = x)`. All-caps are just ugly.
Chris Lutz
An extra set of parentheses around `(x)` in the macro definition is advisable.
caf
@caf - My bad. I usually do that. For what it's worth, I don't see any way it could backfire without the parenthesis - the only operator with lower precedence is `,`, which will cause a completely different (and quite catchable) problem.
Chris Lutz