Why does my Windows Console Close Event Handler time out?

风流意气都作罢 提交于 2020-05-14 02:28:13

问题


I build the following program in VS2017/Windows 10. When I run it, I hit close and ctrl_handler() is called as expected, but after ~three seconds the process is forcefully terminated anyway.

This is a problem because my real application writes large log files and three seconds is not long enough to get them onto disk.

Where is the documentation that describes this behaviour? Its not in those for the CTRL+CLOSE signal.

Where is the timeout set? Can it be modified at the application level? Or with a group policy?

#include <Windows.h>

bool mainThreadRunning;
bool mainThreadFinished;

BOOL ctrl_handler(DWORD event)
{
    if (event == CTRL_CLOSE_EVENT) {
        mainThreadRunning = false;
        while (!mainThreadFinished) {
            Sleep(100);
        }
        return TRUE;
    }
    return FALSE;
}

int main()
{
    mainThreadRunning = true;
    mainThreadFinished = false;

    SetConsoleCtrlHandler((PHANDLER_ROUTINE)(ctrl_handler), TRUE);  // make sure when the user hits the close button in the console we shut down cleanly

    while (true)
    {

    }

    return 0;
}

回答1:


I suppose this is the reference you were looking for:

Unfortunately, this is determined by the OS. There is documentation describing the behavior in the HandlerRoutine Callback docs:

" In this case, no other handler functions are called, and the system displays a pop-up dialog box that asks the user whether to terminate the process. The system also displays this 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 or CTRL_SHUTDOWN_EVENT)."

There is no (at least public, documented) API to change this timeout.

Note:

A process can use the SetProcessShutdownParameters function to prevent the system from displaying a dialog box to the user during logoff or shutdown. In this case,the system terminates the process when HandlerRoutine returns TRUE or when the time-out period elapses.

The operating system intentionally forces termination if it considers handler is taking too much time to complete.

Important note pulled from comments below:

... Ctrl+C is not subject to the time-out (I've tested it, and that's what I am using now).



来源:https://stackoverflow.com/questions/47041407/why-does-my-windows-console-close-event-handler-time-out

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!