在 Win32 上处理 CTRL+C [英] Handle CTRL+C on Win32

查看:71
本文介绍了在 Win32 上处理 CTRL+C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这篇关于在 Win32 上处理 CTRL+C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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