Shutdown Hook c++
Asked Answered
W

4

6

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.

Weidar answered 7/8, 2011 at 18:30 Comment(2)
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 arrivesPillow
As @Drake suggested, I would go for atexit.Corso
S
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.

Senile answered 7/8, 2011 at 18:40 Comment(3)
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)Pillow
Thank you, actually i was afraid of that answereWeidar
also: assert(), abort(), terminate()Nightly
C
3

For normal closing applciation I would suggest

atexit()
Clarkclarke answered 7/8, 2011 at 18:33 Comment(1)
That is only for normal termination.Boonie
K
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.

Kink answered 7/8, 2011 at 18:40 Comment(2)
Above I have assumed that the exit is "normal", i.e. not via e.g. exit() call, or due to segmentation fault, etc.Kink
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.Nightly
F
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.

Fairing answered 8/8, 2011 at 11:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.