1

if a user decides to force close my application(like through the task manager) is there a way i can quickly execute some clean up code before the application closes? i'm coding in c++ btw

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
adam
  • 107
  • 1
  • 13

2 Answers2

2

It depends on how the process is instructed to close. It is possible to do this upon graceful exit, but not for anything forcefully closed.

If the process is closed via TerminateProcess or ExitProcess, you won't be able to perform any graceful cleanup. TerminateProcess is how Task Manager and utilities like Sysinternals pskill end a target process. ExitProcess is called within a process but is not typically used to exit.

If the process has a message pump on one thread (typically the first thread in the process) and no other threads running that are running code whose lifetimes are independent of activity in that thread, then a WM_QUIT message will signal that the process should close (semantically, that the app should close, your process might conceivably stick around for a while for other reasons), and you can run cleanup code upon receiving the message. Depending on your needs, in a windowed app you might consider performing cleanup operations as early as WM_CLOSE or WM_DESTROY.

If you have written code in a DLL, there are notifications that you can handle in DllMain that will allow you to perform last-chance cleanup (DLL_PROCESS_DETACH), which can potentially cover the case of a process exiting without having a message pump. However, this is not a great way to perform cleanup for code that strictly relies on any C/C++ runtime (or any other DLL), as the runtime might be unloaded first.

Last, for any graceful close where you control what runs in WinMain or main, you can always do whatever cleanup you need to do before either function returns, sending control back to the windows subsystem. This is preferred and usually safest for most application needs.

meklarian
  • 6,595
  • 1
  • 23
  • 49
  • Also worth mentioning, there's a pretty good list of the number of ways a process may be terminated an the answer this question: http://stackoverflow.com/a/24095252/118939 But note that all of them short of mangling process memory will map to one of the exit points or Windows performing the same thing as `TerminateProcess` as mentioned in my answer. – meklarian Apr 29 '15 at 05:51
0

If you are using a message pump, handle the WM_QUIT message.

Also: What is the difference between WM_QUIT, WM_CLOSE, and WM_DESTROY in a windows program?

EDIT

Im sorry, I read over the fact that you want to handle termination, eg by the task manager.
This might help you though: How to catch event when Task manager kill your C++ application

Community
  • 1
  • 1
Beta Carotin
  • 1,659
  • 1
  • 10
  • 27