除以零不会抛出 SIGFPE
我有一个小程序执行浮点除以零,所以我期望 SIGFPE。
#include <sys/types.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
void signal_handler (int signo) {
if(signo == SIGFPE) {
std::cout << "Caught FPE\n";
}
}
int main (void) {
signal(SIGFPE,(*signal_handler));
double b = 1.0;
double c = 0.0;
double d = b/c;
std::cout << "d = "<< d << std::endl;
return 0;
}
实际上,我得到了以下输出:
d = inf
gcc version 4.5.2 (Ubuntu/Linaro 4.5.2-8ubuntu4)
在这种情况下我应该怎么做才能抛出 SIGFPE? FP 操作行为取决于哪些因素(编译器标志/CPU 类型等)?
谢谢
I have a small program performing floating-point division by zero, so I expect SIGFPE.
#include <sys/types.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
void signal_handler (int signo) {
if(signo == SIGFPE) {
std::cout << "Caught FPE\n";
}
}
int main (void) {
signal(SIGFPE,(*signal_handler));
double b = 1.0;
double c = 0.0;
double d = b/c;
std::cout << "d = "<< d << std::endl;
return 0;
}
Actually, I got the following output:
d = inf
gcc version 4.5.2 (Ubuntu/Linaro 4.5.2-8ubuntu4)
What should I do to throw SIGFPE in this case? Which factors FP operation behaviour depend on (compiler flags/CPU type and so on)?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
仅当执行整数除以零时,才会收到信号。对于浮点数,除以零是明确定义的。
这实际上在维基百科文章中得到了很好的解释。
You only get a signal if you perform an integer division by zero. For floating point numbers, division by zero is well defined.
This is actually explained rather well in the Wikipedia article.
对于浮点数,您可以通过设置 FPU 控制字来更改此行为。看看
For floating point numbers you can change this behavior by setting up FPU control word. Take a look here
您不会收到信号,因为大多数机器上的默认行为是用 NaN(非数字)和无穷大来污染您的数据。您必须启用浮点异常,具体操作方式取决于机器。查看系统标头
fenv.h
(如果有的话)。函数fesettrapenable
可以在许多机器上捕获浮点异常。不幸的是,没有标准函数可以打开浮点异常处理。
You don't get a signal because the default behavior on most machines is to pollute your data with NaNs (not-a-number) and infinities. You have to enable floating point exceptions, and how you do that is machine specific. Look at the system header
fenv.h
, if you have one. The functionfesettrapenable
enables catching floating point exceptions on many machines.Unfortunately, there is no standard function to turn floating point exceptions handling on.