Detecting that a cmd window is about to close

Is there anyway to tell a program to do something, like write its current state to a file, before exiting semi-unexpectedly?

By semi-unexpectedly I mean like someone clicking the red X at the top right, or someone manually closing the program some other way. Would I need to account for each case individually?

Basically I need to save some data to a file if the program were to suddenly stop running for some reason outside of the program's control.

Thanks
atexit is nonsense here, you should use SetConsoleCtrlHandler() API directly to intercept Ctrl+C or X on the console:
http://msdn.microsoft.com/en-us/library/ms686016(VS.85).aspx
You have 10 seconds to cleanup, after that windows will kill the process no matter what.

If this is a GUI program, you receive WM_CLOSE message when user clicks red X. Just do the cleanup here or even ignore the message, so the program will keep running.


If the program is terminated using Task Manager or taskill or TerminateProcess API then there is no way to abort or even know about it.
Topic archived. No new replies allowed.