5

is there some way to run code on termination, no matter what kind termination (abnormal,normal,uncaught exception etc.)? I know its actually possible in Java, but is it even possible in C++? Im assuming a windows environment.

Sebastian Hoffmann
  • 11,127
  • 7
  • 49
  • 77
  • 3
    It is not possible in Java either -- all processes regardless of language cannot catch signal-9 on linux (and the equivalent on Windows) or run any code when that signal arrives – Soren Aug 07 '11 at 18:44
  • As @Drake suggested, I would go for [atexit](http://www.cplusplus.com/reference/cstdlib/atexit/). – Pantelis Sopasakis Nov 10 '15 at 22:21

4 Answers4

5

No -- if somebody invokes TerminateProcess, your process will be destroyed without further adieu, and (in particular) without any chance to run any more code in the process of shutting down.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
  • 2
    This is the right answer; however as indicated by some of the other answers, you can setup an exit-handler using `atexit()` and you can catch most signals using `signal()` -- however you can never take any action if somebody forces termination ( that would be kill-9 on Linux, and signal 9 is uncatchable) – Soren Aug 07 '11 at 18:43
  • Thank you, actually i was afraid of that answere – Sebastian Hoffmann Aug 07 '11 at 18:51
  • also: assert(), abort(), terminate() – Martin York Aug 07 '11 at 18:51
3

For normal closing applciation I would suggest

atexit()
Drake
  • 3,851
  • 8
  • 39
  • 48
1

One good way to approach the problem is using the C++ RAII idiom, which here means that cleanup operations can be placed in the destructor of an object, i.e.

class ShutdownHook {
  ~ShutdownHook() { 
    // exit handler code 
  }
}; 

int main() { 
  ShutdownHook h; 
  //...
} 

See the Object Lifetime Manager in ACE library. At the linked document, they discuss about the atexit function as well.

amit kumar
  • 20,438
  • 23
  • 90
  • 126
  • Above I have assumed that the exit is "normal", i.e. not via e.g. `exit()` call, or due to segmentation fault, etc. – amit kumar Aug 07 '11 at 18:42
  • 2
    Careful. This is not guaranteed to work. If an exception escapes main() then in is implementation defined whether the stack is unwound. Thus to guarantee this works you must catch all exceptions in main() (putting your code in the try block). You don;t need to do anything just rethrow the exception afterwords. – Martin York Aug 07 '11 at 18:44
0

Not for any kind of termination; there are signals that are designed to not be handled, like KILL on Linux.

These signals are designed to terminate a program that has consumed all memory, or CPU, or some other resources, and has left the computer in a state that makes it difficult to run a handler function.

Fabio A. Correa
  • 1,968
  • 1
  • 17
  • 26