Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I handle exit() calls in 3rd party library code?

I'm working on a C++ application which uses a library written in C by another team. The writers of the library like to call exit() when errors happen, which ends the program immediately without calling the destructors of objects on the stack in the C++ application. The application sets up some system resources which don't automatically get reclaimed by the operating system after the process ends (shared memory regions, interprocess mutexes, etc), so this is a problem.

I have complete source code for both the app and the library, but the library is very well-established and has no unit tests, so changing it would be a big deal. Is there a way to "hook" the calls to exit() so I can implement graceful shutdown for my app?

One possibility I'm considering is making one big class which is the application - meaning all cleanup would happen either in its destructor or in the destructor of one of its members - then allocating one of these big objects on the heap in main(), setting a global pointer to point to it, and using atexit() to register a handler which simply deletes the object via the global pointer. Is that likely to work?

Is there a known good way to approach this problem?

like image 492
bythescruff Avatar asked Jan 07 '13 16:01

bythescruff


Video Answer


2 Answers

In the very worst case, you can always write your own implementation of exit and link it rather than the system's own implementation. You can handle the errors there, and optionally call _exit(2) yourself.

Since you have the library source, it's even easier - just add a -Dexit=myExit flag when building it, and then provide an implementation of myExit.

like image 193
Carl Norum Avatar answered Sep 19 '22 05:09

Carl Norum


install exit handler with atexit and implement the desired behavior

like image 33
bobah Avatar answered Sep 18 '22 05:09

bobah