为SIGFPE设置标志并继续执行忽略FPE
在数值应用程序中,我想知道计算完成后是否发生浮点异常.默认情况下,将以静默方式忽略浮点除法和无效操作.
我的尝试是启用我关心的FPE,通过设置标志来处理SIGFPE并再次禁用它们以允许继续执行:
#include <fenv.h>
#include <signal.h>
#include <stdio.h>
int caught = 0;
struct sigaction old_sa;
/* (2) */ fenv_t fenv_hold;
void sighandler()
{
caught = 1;
printf("Caught in handler, disabling\n");
/* (1) */ fedisableexcept(FE_ALL_EXCEPT);
/* (2) */ feholdexcept(&fenv_hold);
sigaction(SIGFPE, &old_sa, NULL);
}
int main(void)
{
struct sigaction sa;
volatile double a=1, b=0;
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_SIGINFO;
sa.sa_sigaction = sighandler;
sigaction(SIGFPE, &sa, &old_sa);
feenableexcept(FE_DIVBYZERO);
printf("Dividing by zero..\n");
a/=b;
printf("Continuing\n");
}
我采用了两种方法,第一种用(1)标记,第二种用(2)标记.它们都没有按预期工作.
输出:
Dividing by zero..
Caught in handler, disabling
Floating point exception (core dumped)
预期产出:
Dividing by zero..
Caught in handler, disabling
Continuing