在 Win32 上处理 CTRL+C

2021-12-18 00:00:00 winapi c++ console-application

我在 Win32 C++ 控制台程序中处理 CTRL+C 事件时遇到一些问题.

I have some problems with the handling of CTRL+C events, in a Win32 C++ console program.

基本上我的程序是这样的:(基于另一个问题:Windows Ctrl-C - 清理命令行应用程序中的本地堆栈对象)

Basically my program looks like this: (based on this other question: Windows Ctrl-C - Cleaning up local stack objects in command line app)

bool running;

int main() {

    running = true;
    SetConsoleCtrlHandler((PHANDLER_ROUTINE) consoleHandler, TRUE);

    while (running) {
       // do work
       ...
    }

    // do cleanup
    ...

    return 0;
}

bool consoleHandler(int signal) {

    if (signal == CTRL_C_EVENT) {

        running = false;
    }
    return true;
}

问题是根本没有执行清理代码.

The problem is the cleanup code not being executed at all.

处理函数执行后,进程终止,但在主循环后不执行代码.怎么了?

After the execution of the handler function the process is terminated, but without execute the code after the main loop. What's wrong?

根据要求,这是一个类似于我的程序的最小测试用例:http://pastebin.com/6rLK6BU2

as requested, this is a minimal test case similar to my program: http://pastebin.com/6rLK6BU2

我的输出中没有test cleanup-instruction"字符串.

I don't get the "test cleanup-instruction" string in my output.

我不知道这是否重要,我正在使用 MinGW 进行编译.

I don't know if this is important, I'm compiling with MinGW.

EDIT 2: 测试用例程序的问题是 Sleep() 函数的使用.没有它,程序会按预期工作.

EDIT 2: The problem with the test case program is the use of the Sleep() function. Without it the program works as expected.

在 Win32 中,函数处理程序在另一个线程中运行,因此当处理程序/线程结束其执行时,主线程正在休眠.大概这就是进程中断的原因?

In Win32 the function handler runs in another thread, so when the handler/thread ends its execution the main thread is sleeping. Probably this is the cause of process interruption?

推荐答案

以下代码对我有用:

#include <windows.h> 
#include <stdio.h> 

BOOL WINAPI consoleHandler(DWORD signal) {

    if (signal == CTRL_C_EVENT)
        printf("Ctrl-C handled
"); // do cleanup

    return TRUE;
}

int main()
{
    running = TRUE;
    if (!SetConsoleCtrlHandler(consoleHandler, TRUE)) {
        printf("
ERROR: Could not set control handler"); 
        return 1;
    }

    while (1) { /* do work */ }

    return 0;
}

相关文章