简体   繁体   中英

How to properly handle SIGBREAK when closing console?

I have to catch the click on close button of console event, which corresponds to ctrl-break event SIGBREAK but apparently there is a kind of timeout which does not allows me to do anything longer than 5 seconds, after what program seems to be aborted (so the message "Properly ended !" will never happend).

How can I force the system to perform closing operations until the end (or to extend the timeout to 60 seconds) ?

Note: with the same method, I can successfully handle CTRL+C event ( SIGINT ) using fflush(stdout); just before doStuffs();

Note 2: my code is based on this answer: https://stackoverflow.com/a/181594/1529139

#include <csignal>

void foo(int sig)
{
    signal(sig, foo); // (reset for next signal)

    // do stuffs which takes aboutly 15 seconds
    doStuffs();

    cout << "Properly ended !";
}

int main(DWORD argc, LPWSTR *argv)
{
    signal(SIGBREAK, foo);
    myProgramLoop();
}

I believe the timeout is fixed and there is no way to modify it, see API reference :

The system also displays the dialog box if the process does not respond within a certain time-out period (5 seconds for CTRL_CLOSE_EVENT, and 20 seconds for CTRL_LOGOFF_EVENT and CTRL_SHUTDOWN_EVENT).

A process can use the SetProcessShutdownParameters function to prevent the CTRL_LOGOFF_EVENT and CTRL_SHUTDOWN_EVENT dialog box from being displayed. In this case, the system just terminates the process when a HandlerRoutine returns TRUE or when the time-out period elapses.

How about an alternative approach, just disable the close button of your console window:

GUITHREADINFO info = {0};
info.cbSize=sizeof(info);
GetGUIThreadInfo(NULL, &info);
HMENU hSysMenu = GetSystemMenu(info.hwndActive, FALSE);
EnableMenuItem(hSysMenu, SC_CLOSE, MF_GRAYED);

Now you can safely handling closing through Ctrl-C or other keyboard input instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM