How can I guarantee the execution of cleanup code in Windows C ++ (SIGINT, bad alloc and closed window)

I have a console program on Windows C ++, and if I do not call ReleaseDriver()at the end of my program, some hardware goes into a bad state and cannot be reused without a reboot. I would like to make sure that it ReleaseDriver()starts even if the program crashes, for example, if I clicked Ctrl+Cor closed the console window.

I can use signal()to create a signal handler for SIGINT. This works great, although at the end of the program an unpleasant error appears "Win32 exception fixed ...".

I do not know how to handle the case of closing the console, and (more importantly). I do not know how to handle exceptions caused by bad memory access, etc.

Thanks for any help!

+3
source share
3 answers

On Windows, you can create a raw exception filter by calling SetUnhandledExceptionFilter () . After executing any time an exception is thrown that is not handled somewhere in your application, your handler will be called.

Your handler can be used to free resources, create dump files (see MiniDumpWriteDump ), or what you need to do to make sure it is done.

, "gotchas", , . :

  • CRT, new
  • - , , Windows , . , .

Windows API. sprintf, new, delete... , WINAPI, , , .

- static. sprintf, . , , .

+3

, , Ctrl + C SetConsoleCtrlHandler:

#include <windows.h>

BOOL CtrlHandler(DWORD)
{
    MessageBox(NULL, "Program closed", "Message", MB_ICONEXCLAMATION | MB_OK);
    exit(0);
}

int main()
{
    SetConsoleCtrlHandler((PHANDLER_ROUTINE)&CtrlHandler, TRUE);
    while (true);
}

, bad_alloc, main try. Catch std::exception&, , ++ catch (...). , , , , .

undefined.:)

+2

( ). , . L1 , .

- , ( WaitForSingleObject ). , ( - ).

+1
source

Source: https://habr.com/ru/post/1735968/


All Articles