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

查看:1295
本文介绍了在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.

编辑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\n"); // do cleanup

    return TRUE;
}

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

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

    return 0;
}

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

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