You can surely catch SIGTERM . But it's not a problem. You want to override the exit() call.
This is not possible in any portable or standard agreement. exit() is one of the functions that do not return to the caller. This is usually done using __attribute__((noreturn)) in gcc, and C11 introduces the _Noreturn macro for the same purpose.
Trying to return from such a function, for example exit() , undefined behavior .
There are several options that I can think of:
- Compile and replace your function:
gcc -Dexit=not_exit file.c - Write a hook function for
exit() . See here for an example. An implementation of the hook function may not work at all, since this noreturn exists in most libc implementations prior to C11 _Noreturn . - Use GNU ld, as suggested by @evading. I believe this is equivalent to the above, but the linker does half the work for you.
Changing <stdlib.h> to remove the _Noreturn attribute (or its equivalent) for the exit() function may make it work. None of them are guaranteed to work. We are already well entering the land of UB.
Another option is the install atexit() handler, which can be useful if you want to do something before exit() .
A more robust approach would be to change the library if you do not call exit() , but instead return an error code. In my opinion, either the library is poorly designed that it accidentally exits by itself, or there is probably a good reason why the library exits (due to some fatal error), and your application should not continue further, what are you trying to do .
source share