#include <iostream>
#include <signal.h>
#include <fenv.h>
#include <string.h>
void signal_handler(int sig, siginfo_t *siginfo, void* context)
{
std::cout << " signal_handler " << fetestexcept(FE_ALL_EXCEPT) << std::endl;
throw "exception";
}
void divide() {
float a = 1000., b = 0., c, f = 1e-300;
c = a / b;
std::cout << c << " and f = " << f << std::endl;
}
void init_sig_hanlder() {
feenableexcept(FE_ALL_EXCEPT);
struct sigaction sa, initial_sa;
sa.sa_sigaction = &signal_handler ;
sigemptyset( &sa.sa_mask ) ;
sa.sa_flags = SA_SIGINFO; // man sigaction(3) // allows for void(*)(int,siginfo_t*,void*) handler
sigaction(SIGFPE, &sa, &initial_sa);
}
int main(int argc, char** argv) {
init_sig_hanlder();
while(true)
{
try {
sleep(1);
divide();
}
catch(const char * a) {
std::cout << "Exception in catch: " << a << std::endl;
}
catch(...) {
std::cout << "Exception in ..." << std::endl;
}
}
return 0;
}
在Linux/g++4.2上产生如下结果:
信号处理程序 0
捕获异常:exception
inf 和 f = 0
inf 和 f = 0
inf 和 f = 0
inf 和 f = 0
因此,第一次执行信号处理程序,但下一个 fp 异常不会再次触发处理程序。我哪里错了?
最佳答案
我不认为在信号处理程序中抛出异常是好的做法。操作系统期望信号处理程序返回
,因为在调用它的处理程序时信号被阻塞。通过抛出异常,您可以阻止系统解锁信号。
关于c++ - 为什么我的 linux 信号处理程序只运行一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2920371/