Is there a difference between the on_exit() and atexit() functions? - c

Is there any difference between
int on_exit(void (*function)(int , void *), void *arg);
and
int atexit(void (*function)(void));
other than the fact that the function used by on_exit gets the exit status?
That is, if I don't care about the exit status, is there any reason to use one or the other?
Edit: Many of the answers warned against on_exit because it's non-standard. If I'm developing an app that is for internal corporate use and guaranteed to run on specific configurations, should I worry about this?

You should use atexit() if possible. on_exit() is nonstandard and less common. For example, it's not available on OS X.
Kernel.org - on_exit():
This function comes from SunOS 4, but is also present in libc4, libc5 and
glibc. It no longer occurs in Solaris (SunOS 5). Avoid this function, and
use the standard atexit(3) instead.

According to this link I found, it seems there are a few differences. on_exit will let you pass in an argument that is passed in to the on_exit function when it is called... which might let you set up some pointers to do some cleanup work on when it is time to exit.
Furthermore, it appears that on_exit was a SunOS specific function that may not be compatible on all platforms... so you may want to stick with atexit, despite it being more restrictive.

The difference is that atexit is C and on_exit is some weird extension available on GNU and who-knows-what-other Unixy systems (but NOT part of POSIX).

#Nathan, I can't find any function that will return the exit code for the current running process. I expect that it isn't set yet at the point when atexit() is called, anyway. By this I mean that the runtime knows what it is, but probably hasn't reported it to the OS. This is pretty much just conjecture, though.
It looks like you will either need to use on_exit() or structure your program so that the exit code doesn't matter. It would not be unreasonable to have the last statement in your main function flip a global exited_cleanly variable to true. In the function you register with atexit(), you could check this variable to determine how the program exited. This will only give you two states, but I expect that would be sufficient for most needs. You could also expand this type of scheme to support more exit states if necessary.

#Nathan
First, see if there is another API call to determine exit status... a quick glance and I don't see one, but I am not well versed in the standard C API.
An easy alternative is to have a global variable that stores the exit status... the default being an unknown error cause (for if the program terminates abnormally). Then, when you call exit, you can store the exit status in the global and retrieve it from any atexit functions. This requires storing the exit status diligently before every exit call, and clearly is not ideal, but if there is no API and you don't want to risk on_exit not being on the platform... it might be the only option.

Related

Writing my own longjmperror() in C

I was looking at the manual for longjmp and in the Errors part it says this:
ERRORS
If the contents of the env are corrupted, or correspond to an environment that has already returned, the longjmp() routine calls the routine longjmperror(3). If longjmperror()
returns, the program is aborted (see abort(3)). The default version of longjmperror() prints the message ``longjmp botch'' to standard error and returns. User programs wishing to exit more gracefully should write their own versions of longjmperror().
How would i write my own version of longjmperror? From what i know in C you can't override functions and i really need the long jump to exit in a specific way when it doesn't find the point to jump to.
On Mac OS X (10.9.2, Mavericks) at any rate, the prototype for longjmperror() is:
void longjmperror(void);
You write a function with that signature. It must not return (or, rather, if it does, the program will be abort()ed). What you do in that function is your business, but bear in mind that things have gone moderately catastrophically wrong for the function to be called at all). It might log an error to your log file, or just write a more meaningful message before exiting (instead of aborting and perhaps core dumping).
You link the object file containing the function ahead of the system library. You are normally not expected to replace system functions, but this is one you are intended to override.

How to implement analogue of exit() functions? -std=c99

I'm writing a university project. Writing in standard C99. One of the requirements is the lack of exit(); function. Is it possible to implement a similar function?
I tried to make a function that calls main with a minus argc to detect exit. It was a stupid attempt, because the first main continues.
Just the description of the project specified that the scores will be reduced for the use of exit by exit().I understand that it asks me to code running through pointers and returns an error in the return values ​​of the function. I'm more interested in the practice. Only for myself.
I think you misunderstood the requirement: They probably said something like do not use exit(). This does not mean you are supposed to implement your own exit(), quite to the contrary: they probably mean that the only exit-point of your program shall be the end of your main-function (or a return-statement within the main function) which is considered good programming style.
exit() is a system level facility that you can't implement on your own without knowing how the operating system implements it (Linux? Windows? embedded system?) works. As Daniel Fischer mentioned, you could call abort() which will basically do the same thing that exit will do and quit the program.
There are other "hacks" to get your program to abort without calling exit() explicitly, but these are just hacks and should not be used in production code.
Create a C++ function with C linkage and throw an exception
extern "C" MyExit() { throw std::exception(); }
Call signal() with SIGKILL
Call abort()
Write some assembly code to unwind the call stack until it gets to the function that called main and insert the return value in to the proper return register and go from there. I don't think you can do this in pure C, as the ABI is not accessible directly. But at least this would be only method that doesn't involve the operating system (just the ABI).

Where can I find the list of non-reentrant functions provided in gnu libc?

I am now porting an single-threaded library to support multi-threads, and I need the whole list of functions that use local static or global variables.
Any information is appreciated.
Check the manual page for each function you use ... the non-thread-safe ones will be identified as such, and the manual page will mention a thread safe version when there is one (e.g., readdir_r). You could extract the list by running a script over the man pages.
Edit: Although my answer has been accepted, I fear that it is inaccurate and possibly dangerous. For example, while strerror_r mentions that it is a thread safe version of strerror, strerror itself says nothing about thread safety ... what it says instead is "the string might be overwritten", which merely implies that it isn't thread-safe. So you need to search for at least "might be overwritten" as well as "thread", but there's no guarantee that even that will be complete.
Its always a good idea to know if a particular function is reentrant or not, but you must also consider the situation when you may call several reentrant functions from a shared piece of code from multiple threads, which could also lead to problems when using shared data.
So, if you have any data shared between threads, the data must be "protected" irregardless of the fact that the functions being called are reentrant.
Consider the following function:
void yourFunc(CommonObject *o)
{
/* This function is NOT thread safe */
reentrant_func1(o->propertyA);
reentrant_func2(o->propertyA);
}
If this function is not mutex protected, you will get undesired behavior in a multithreaded application, irregardless of the fact that func1 and func2 are reentrant.

Should errno/perror methodology be used today to detect errors?

I know many questions have been asked previously about error handling in C but this is specifically about errno stuff.
I want to ask whether we should use the errno/perror functionality to handle errors gracefully at runtime.I am asking this because MSVC uses it and Win32 api also uses it heavily.I don't know anything about gcc or 'linux api'.Today both gcc and MSVC say that errno/perror can be used safely in a multithreaded environment.So what's your view?
thanks.
Note that using errno alone is a bad idea: standard library functions invoke other standard library functions to do their work. If one of the called functions fails, errno will be set to indicate the cause of the error, and the library function might still succeed, if it has been programmed in a manner that it can fall back to other mechanisms.
Consider malloc(3) -- it might be programmed to try mmap(.., MAP_PRIVATE|MAP_ANONYMOUS) as a first attempt, and if that fails fall back to sbrk(2) to allocate memory. Or consider execvp(3) -- it may probe a dozen directories when attempting to execute a program, and many of them might fail first. The 'local failure' doesn't mean a larger failure. And the function you called won't set errno back to 0 before returning to you -- it might have a legitimate but irrelevant value left over from earlier.
You cannot simply check the value of errno to see if you have encountered an error. errno only makes sense if the standard library function involved also returned an error return. (Such as NULL from getcwd(3) or -1 from read(2), or "a negative value" from printf(3).)
But in the cases when standard library functions do fail, errno is the only way to discover why they failed. When other library functions (not supplied by the standard libraries) fail, they might use errno or they might provide similar but different tools (see e.g. ERR_print_errors(3ssl) or gai_strerror(3).) You'll have to check the documentation of the libraries you're using for full details.
I don't know if it is really a question of "should" but if you are programming in C and using the low level C/posix API, there really is no other option. Of course you can wrap it up if this offends your stylistic sensibilities, but under the hood that is how it has to work (at least as long as POSIX is a standard).
In Linux, errno is safe to read/write in multiple thread or process, but not with perror(). It's a standard library that not re-entrant.

Why does avr-gcc bother to save the register state when calling main()?

The main() function in an avr-gcc program saves the register state on the stack, but when the runtime calls it I understand on a microcontroller there isn't anything to return to. Is this a waste of RAM? How can this state saving be prevented?
How can the compiler be sure that you aren't going to recursively call main()?
It's all about the C-standard.
Nothing forbids you from exiting main at some time. You may not do it in your program, but others may do it.
Furthermore you can register cleanup-handlers via the atexit runtime function. These functions need a defined register state to execute properly, and the only way to guarantee this is to save and restore the registers around main.
It could even be useful to do this:
I don't know about the AVR but other micro-controllers can go into a low power state when they're done with their job and waiting for a reset. Doing this from a cleanup-handler may be a good idea because this handler gets called if you exit main the normal way and (as far as I now) if your program gets interrupted via a kill-signal.
Most likely main is just compiled in the same was as a standard function. In C it pretty much needs to be because you might call it from somewhere.
Note that in C++ it's illegal to call main recursively so a c++ compiler might be able to optimize this more. But in C as your question stated it's legal (if a bad idea) to call main recursively so it needs to be compiled in the same way as any other function.
How can this state saving be prevented?
The only thing you can do is to write you own C-Startup routine. That means messing with assembler, but you can then JUMP to your main() instead of just CALLing it.
In my tests with avr-gcc 4.3.5, it only saves registers if not optimizing much. Normal levels (-Os or -O2) cause the push instructions to be optimized away.
One can further specify in a function declaration that it will not return with __attribute__((noreturn)). It is also useful to do full program optimization with -fwhole-program.
The initial code in avr-libc does use call to jump to main, because it is specified that main may return, and then jumps to exit (which is declared noreturn and thus generates no call). You could link your own variant if you think that is too much. exit() in turn simply disables interrupts and enters an infinite loop, effectively stopping your program, but not saving any power. That's four instructions and two bytes of stack memory overhead if your main() never returns or calls exit().

Resources