我们有一个处理错误报告许多方面的库。我一直负责将这个库移植到Linux上。当运行我的小测试套件时,其中一个测试失败。下面显示了一个简化版本的测试。
// 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没有捕获处理程序。
发布于 2018-05-09 17:04:51
信号与C ++的例外完全不同。你不能使用C ++ try / catch块来处理信号。具体来说,信号是POSIX的概念,而不是C ++语言的概念。内核将信号异步传送到应用程序,而C ++异常是由C ++标准定义的同步事件。
你在POSIX信号处理程序中可以轻松执行的操作相当有限。一种常见的策略是sig_atomic_t
在信号处理程序中设置一个全局标志类型为1,然后可能longjmp
为适当的执行路径。
发布于 2018-05-09 18:08:22
此代码演示了一种将异常抛出信号处理程序的技术移入代码中的技术。
#include <iostream>
#include <csignal>
#include <csetjmp>
using namespace std;
jmp_buf gBuffer; // A buffer to hold info on where to jump to
void catch_signal(int signalNumber)
{
//signal(SIGINT, SIG_DFL); // Switch to default handling
signal(SIGINT, catch_signal); // Reactivate this handler.
longjmp // Jump back into the normal flow of the program
(
gBuffer, // using this context to say where to jump to
signalNumber // and passing back the value of the signal.
);
}
int test_signal()
{
signal(SIGINT, catch_signal);
try
{
int sig;
if ((sig = setjmp(gBuffer)) == 0)
{
cout << "before raise\n";
raise(SIGINT);
cout << "after raise\n";
}
else
{
// This path implies that a signal was thrown, and
// that the setjmp function returned the signal
// which puts use at this point.
// Now that we are out of the signal handler it is
// normally safe to throw what ever sort of exception we want.
throw(sig);
}
}
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;
}
https://stackoverflow.com/questions/-100008434
复制相似问题