Windows handling CTRL+C in different thread?
Here is a simple application that handled CTRL+C signal both on linux and windows:
#include <QtCore/QCoreApplication>
#include <QDebug>
#include <QThread>
void SigIntHandler()
{
qDebug()<<"SigInt ThreadID: "<<QThread::currentThreadId();
qApp->quit();
}
#ifdef __linux__
#include <signal.h>
void unix_handler(int s)
{
//svakako je SIGINT, ali da ne javlja warning da se s ne koristi
if (s==SIGINT)
SigIntHandler();
}
#else
#include <windows.h>
BOOL WINAPI WinHandler(DWORD CEvent)
{
switch(CEvent)
{
case CTRL_C_EVENT:
SigIntHandler();
break;
}
return TRUE;
}
#endif
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
//kod za hvatanje CTRL+C - unix i windows
#ifdef __linux__
signal(SIGINT, &unix_handler);
#else
SetConsoleCtrlHandler((PHANDLER_ROUTINE)WinHandler, TRUE);
#endif
qDebug()<<"Main ThreadID: "<<QThread::currentThreadId();
return a.exec();
}
After compiling and running it on linux (Debian Squeeze), I get following output:
/Test-build-desktop$ ./Test
Main ThreadID: 140105475446560
^CSigInt ThreadID: 14010开发者_如何学Go5475446560
/Test-build-desktop$ ./Test
Main ThreadID: 140369579480864
^CSigInt ThreadID: 140369579480864
/Test-build-desktop$ ./Test
Main ThreadID: 140571925509920
^CSigInt ThreadID: 140571925509920
And that's what I've expected (SigIntHandler method runs on main thread). But when I compile and execute same code on Windows 7, I get this:
d:\Test-build-desktop\debug>Test.exe
Main ThreadID: 0x5a8
SigInt ThreadID: 0x768
d:\Test-build-desktop\debug>Test.exe
Main ThreadID: 0x588
SigInt ThreadID: 0x1434
d:\Test-build-desktop\debug>Test.exe
Main ThreadID: 0x1170
SigInt ThreadID: 0xc38
As you can see, here SigIntHandler method is executed in different thread then main ... And that creates me many problems. So my question is - is it possible to force SigIntHandler to run in main thread on windows ? Am I maybe catching siging wrong ?
Thanks !!
From MSDN topic HandlerRoutine:
A HandlerRoutine function is an application-defined function used with the SetConsoleCtrlHandler
function. A console process uses this function to handle control signals received by the process. When the signal is received, the system creates a new thread in the process to execute the function.
So, the answer is: this is impossible.
Read the following link for an interesting take on this: http://blogs.msdn.com/b/oldnewthing/archive/2008/07/28/8781423.aspx
精彩评论