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?
exit
when compiling the C library - no need to modify the code at all. I'll still need to implement the ability to clean up the entire app from a global handler, but still, this is the best answer so far. – Comminute