1

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();
}
Community
  • 1
  • 1
56ka
  • 1,463
  • 1
  • 21
  • 37

1 Answers1

1

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.

Community
  • 1
  • 1
snowcrash09
  • 4,694
  • 27
  • 45
  • So does this mean there is no possibility to close a console in a safe way ? (using close button or if is is terminated by another process) – 56ka Aug 19 '14 at 11:55
  • 1
    Well you can close safely, but you have to do it within the 5-second grace period. There is no way to extend this as [Microsoft wants to avoid the arms race](http://blogs.msdn.com/b/oldnewthing/archive/2004/02/16/73780.aspx). – snowcrash09 Aug 20 '14 at 10:07