C在win32的console下响应CTRL+C
http://blog.csdn.net/trojanpizza/article/details/6656321
控制台程序 Ctrl+C 异常问题 First-chance exception in ***.exe [Kernel32.dll].....
//编写一个win32控制台程序 需要处理Ctrl+C的中断事件。但在Debug模式下,按Ctrl+C 会提示上述异常。
//下面两种方式,都会出现。不知道是什么原因。
#include "stdafx.h"
#include <signal.h>
#include <stdlib.h>
#include <windows.h>
//方式一
void do_signal(int signo)
{
printf("reveived signal %d/n",signo);
exit(0);
}
int main(int argc, char* argv[])
{
signal(SIGBREAK,do_signal);
signal(SIGINT,do_signal);
while(1)
{
;
}
return 0;
}
//方式二
BOOL WINAPI ConsoleHandler(DWORD CEvent)
{
switch(CEvent)
{
case CTRL_C_EVENT:
MessageBox(NULL,"CTRL + C received!", "signal", MB_OK);
break;
case CTRL_BREAK_EVENT:
MessageBox(NULL,"CTRL+BREAK received!", "signal", MB_OK);
break;
case CTRL_CLOSE_EVENT:
MessageBox(NULL,"Program being closed!", "signal", MB_OK);
break;
case CTRL_LOGOFF_EVENT:
MessageBox(NULL,"User is logging off!", "signal", MB_OK);
break;
case CTRL_SHUTDOWN_EVENT:
MessageBox(NULL,"User is logging off!", "signal", MB_OK);
break;
}
return TRUE;
}
int main(int argc, char* argv[])
{
char buf[256];
if (SetConsoleCtrlHandler((PHANDLER_ROUTINE)ConsoleHandler, TRUE) == FALSE)//
{
printf("Unable to install event handler!/n");
return -1;
}
// GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0);
scanf("%s", buf);
return 0;
}
把问题记录下来,希望大家给予指点。