为什么我的Windows控制台关闭事件处理程序超时? [英] Why does my Windows Console Close Event Handler time out?

查看:215
本文介绍了为什么我的Windows控制台关闭事件处理程序超时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在VS2017 / Windows 10中构建了以下程序。运行该程序时,我按了close并按预期方式调用了 ctrl_handler(),但在大约三秒钟后,

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.

在哪里描述此行为的文档?它不在用于CTRL + CLOSE信号的

超时设置在哪里?可以在应用程序级别进行修改吗?还是使用组策略?

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;
}


推荐答案

我想这是您要查找的参考


不幸的是,这由操作系统确定。在 HandlerRoutine回调文档:


"在这种情况下,不会调用其他任何处理程序函数,并且系统会显示一个弹出对话框,询问用户是否终止该进程。如果该进程在特定的超时时间内没有响应(对于CTRL_CLOSE_EVENT为5秒,对于CTRL_LOGOFF_EVENT或CTRL_SHUTDOWN_EVENT为20秒),系统也将显示此对话框。

" 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)."

没有(至少公开的,有文件记录的)API来更改此超时。

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

注意:


进程可以使用 SetProcessShutdownParameters 函数来防止系统在注销或关闭过程中向用户显示对话框。在这种情况下,当HandlerRoutine返回TRUE 或超时时间结束时,系统将终止该过程。

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 不受超时限制(我已经测试过了,这就是我现在正在使用的时间)。

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

这篇关于为什么我的Windows控制台关闭事件处理程序超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆