在信号处理程序内抛出异常 [英] Throwing an exception from within a signal handler
问题描述
我们有一个库,处理错误报告的许多方面。我被任命将这个库移植到Linux。当通过我的小测试套件运行时,其中一个测试失败。
We have a library that deals with many aspects of error reporting. I have been tasked to port this library to Linux. When running though my little test suite, one of the tests failed. A simplified version of the test appears below.
// Compiler: 4.1.1 20070105 RedHat 4.1.1-52
// Output: Terminate called after throwing an instance of 'int' abort
#include <iostream>
#include <csignal>
using namespace std;
void catch_signal(int signalNumber)
{
signal(SIGINT, SIG_DFL);
throw(signalNumber);
}
int test_signal()
{
signal(SIGINT, catch_signal);
try
{
raise(SIGINT);
}
catch (int &z)
{
cerr << "Caught exception: " << z << endl;
}
return 0;
}
int main()
{
try
{
test_signal();
}
catch (int &z)
{
cerr << "Caught unexpected exception: " << z << endl;
}
return 0;
}
我的期望是捕获异常将显示。实际发生的是,程序终止,因为没有捕获处理程序似乎存在的抛出的int。
My expectation is that the Caught exception: message will be displayed. What actually happens is that the program terminates as no catch handler appears to be present for the thrown int.
有几个问题似乎相关的SO。
我发现了一些相关的Google页面。
智慧似乎归结为。
There are a few questions on SO that seem related. I found a number of Google pages that were related. The 'wisdom' seems to boil down to.
- Ya不能从信号处理程序抛出异常, b $ b处理程序使用自己的堆栈运行,因此没有定义处理程序。
- Ya可以从信号处理程序抛出异常,只是在堆栈上重建一个假的
框架,你很好去。 - Ya,我们一直这样做。它适用于我在平台X
-
Ya,以前可用的gcc,但似乎没有工作任何
更多。请尝试使用 -fnon-call-exceptions 和 -fnon-call-exceptions 选项。
代码在我们的AIX / TRU64 / MSVC编译器/环境中正常工作。它在我们的Linux环境中失败。
The code works correctly on our AIX/TRU64/MSVC compiler/environments. It fails in our Linux environment.
我正在寻找有助于解决此问题的建议,在Linux上的行为将匹配我的其他平台,或某种排序或解决方法,可能实现相同的功能。
让程序核心转储信号,不是一个可行的选项。
推荐答案
信号完全 不同于C ++异常。你不能使用C ++ try / catch块来处理信号。具体来说,信号是POSIX概念,而不是C ++语言概念。信号是由内核异步地传递到你的应用程序,而C ++异常是由C ++标准定义的同步事件。
Signals are totally different than C++ exceptions. You can't use a C++ try/catch block to handle a signal. Specifically, signals are a POSIX concept, not a C++ language concept. Signals are delivered asynchronously to your application by the kernel, whereas C++ exceptions are synchronous events defined by the C++ standard.
你在一个可移植的POSIX信号处理程序。一个常见的策略是具有类型 sig_atomic_t
的全局标志,它将在信号处理程序中设置为1,然后可能 longjmp
到相应的执行路径。
You are quite limited in what you can do portably in a POSIX signal handler. A common strategy is to have a global flag of type sig_atomic_t
which will be set to 1 in the signal handler, and then possibly longjmp
to the appropriate execution path.
查看这里帮助编写正确的信号处理程序。
See here for help writing proper signal handlers.
这篇关于在信号处理程序内抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!