【发布时间】:2015-03-16 07:27:42
【问题描述】:
我生活在一个带有 Win7/MSVC 2010sp1 的环境中,两个不同的 Linux 机器 (Red Hat) 带有 g++ 版本(4.4.7、4.1.2),以及带有 xlc++ (08.00.0000.0025) 的 AIX。
不久前,有人要求我们将一些代码从 AIX 迁移到 Linux。没过多久,Linux 就有些不同了。通常当一个信号被抛出时,我们会处理它并抛出一个 C++ 异常。这没有按预期工作。
Long story short, throwing c++ exceptions from a signal handler isn't going to work.
稍后,我整理了一个使用 setjmp/longjmp 将异常移出处理程序的修复程序。经过一番测试,该死的东西适用于所有平台。在强制性的一轮立方体快乐舞蹈之后,我开始设置一些单元测试。哎呀。
我的一些测试在 Linux 上失败了。我观察到 raise 函数只工作一次。使用 SIGILL 进行两次测试,第一次通过,第二次失败。我拿出一把斧头,开始砍掉代码以尽可能多地去除杂物。这就产生了这个更小的例子。
#include <csetjmp>
#include <iostream>
#include <signal.h>
jmp_buf mJmpBuf;
jmp_buf *mpJmpBuf = &mJmpBuf;
int status = 0;
int testCount = 3;
void handler(int signalNumber)
{
signal(signalNumber, handler);
longjmp(*mpJmpBuf, signalNumber);
}
int main(void)
{
if (signal(SIGILL, handler) != SIG_ERR)
{
for (int test = 1; test <= testCount; test++)
{
try
{
std::cerr << "Test " << test << "\n";
if ((status = setjmp(*mpJmpBuf)) == 0)
{
std::cerr << " About to raise SIGILL" << "\n";
int returnStatus = raise(SIGILL);
std::cerr << " Raise returned value " << returnStatus
<< "\n";
}
else
{
std::cerr << " Caught signal. Converting signal "
<< status << " to exception" << "\n";
std::exception e;
throw e;
}
std::cerr << " SIGILL should have been thrown **********\n";
}
catch (std::exception &)
{ std::cerr << " Caught exception as expected\n"; }
}
}
else
{ std::cerr << "The signal handler wasn't registered\n"; }
return 0;
}
对于 Windows 和 AIX 框,我得到了预期的输出。
Test 1
About to raise SIGILL
Caught signal. Converting signal 4 to exception
Caught exception as expected Test 2
About to raise SIGILL
Caught signal. Converting signal 4 to exception
Caught exception as expected Test 3
About to raise SIGILL
Caught signal. Converting signal 4 to exception
Caught exception as expected
对于两个 Linux 机器,它看起来像这样。
Test 1
About to raise SIGILL
Caught signal. Converting signal 4 to exception
Caught exception as expected
Test 2
About to raise SIGILL
Raise returned value 0
SIGILL should have been thrown **********
Test 3
About to raise SIGILL
Raise returned value 0
SIGILL should have been thrown **********
所以,我真正的问题是“这是怎么回事?”
我的反驳问题是:
- 还有其他人观察到这种行为吗?
- 我应该怎么做才能尝试解决这个问题?
- 我还应该注意哪些其他事项?
【问题讨论】:
标签: linux windows unix signals aix