問題描述
我在 Win32 C++ 控制臺(tái)程序中處理 CTRL+C 事件時(shí)遇到一些問題.
I have some problems with the handling of CTRL+C events, in a Win32 C++ console program.
基本上我的程序是這樣的:(基于另一個(gè)問題:Windows Ctrl-C - 清理命令行應(yīng)用程序中的本地堆棧對(duì)象)
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;
}
問題是根本沒有執(zhí)行清理代碼.
The problem is the cleanup code not being executed at all.
處理函數(shù)執(zhí)行后,進(jìn)程終止,但在主循環(huán)后不執(zhí)行代碼.怎么了?
After the execution of the handler function the process is terminated, but without execute the code after the main loop. What's wrong?
根據(jù)要求,這是一個(gè)類似于我的程序的最小測(cè)試用例: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 進(jìn)行編譯.
I don't know if this is important, I'm compiling with MinGW.
EDIT 2: 測(cè)試用例程序的問題是 Sleep()
函數(shù)的使用.沒有它,程序會(huì)按預(yù)期工作.
EDIT 2: The problem with the test case program is the use of the Sleep()
function. Without it the program works as expected.
在 Win32 中,函數(shù)處理程序在另一個(gè)線程中運(yùn)行,因此當(dāng)處理程序/線程結(jié)束其執(zhí)行時(shí),主線程正在休眠.大概這就是進(jìn)程中斷的原因?
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?
推薦答案
以下代碼對(duì)我有用:
#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;
}
這篇關(guān)于在 Win32 上處理 CTRL+C的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!