我有兴趣提出浮点异常,如Division by zero
, Overflow
,Underflow
等。
我认为,如果我们可以在浮点异常发生时更改陷阱的默认行为,我想做的事情是可能的。
我在fenv.h
. 首先,我使用启用中断
feenableexcept
,然后使用feraiseexcept
.
#define _GNU_SOURCE
#include <fenv.h>
#include <stdio.h>
int main(void) {
feenableexcept(FE_UNDERFLOW);
feraiseexcept(FE_OVERFLOW);
return 0;
}
终端中显示的消息是
Floating point exception (core dumped)
而不是这个,我想要这个表格的信息
Overflow
我也尝试过处理 SIGFPE。由于对于每个浮点异常,都会引发相同的信号 SIGPE,因此它无助于区分不同的信号原因。Stack overflow 上有一个类似的问题,但没有任何令人满意的答案。
我们可以使用 fetestexcept(FE_OVERFLOW) ,但必须在每次浮点运算后明确写入以检查溢出。
注意:我编译我的程序使用
gcc test_float -lm
编辑:
我尝试捕捉 SIGFPE 并编写了这个程序
#define _GNU_SOURCE
#include <fenv.h>
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
void catch_fpe (int sig) {
//#pragma STDC FENV_ACCESS ON
printf("i am in catch_fpe\n");
if(fetestexcept(FE_OVERFLOW))
printf("OVERFLOW\n");
else if(fetestexcept(FE_UNDERFLOW))
printf("UNDERFLOW\n");
else if(fetestexcept(FE_DIVBYZERO))
printf("DIVBYZERO\n");
else if(fetestexcept(FE_INVALID))
printf("INVALID OPERATION\n");
else if(fetestexcept(FE_INEXACT))
printf("INEXACT RESULT\n");
exit(0);
}
int main()
{
feclearexcept(FE_ALL_EXCEPT);
feenableexcept(FE_INVALID |
FE_DIVBYZERO |
FE_OVERFLOW |
FE_UNDERFLOW);
signal(SIGFPE, catch_fpe);
feraiseexcept(FE_DIVBYZERO);
}
它没有按我的预期工作。输出是
i am in catch_fpe
它也应该显示DIVBYZERO
。