Handle CTRL+C on Win32(在 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Win32 上处理 CTRL+C


基础教程推荐
- 我有静态或动态 boost 库吗? 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 这个宏可以转换成函数吗? 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何检查GTK+3.0中的小部件类型? 2022-11-30