如何生成始终触发信号 SIGFPE(div by zero) 的代码? [英] How to produce codes that always trigger signal SIGFPE(div by zero)?
问题描述
我需要编写一个单元测试,它应该总是触发除以零信号 (SIGFPE),这样我就可以测试和比较有/没有我的信号捕获模块会发生什么.
I need to code a unit-test that should always trigger a divied by zero signal(SIGFPE), so I can test and compare what would happen with/without my signal catching module.
我的 Linux 信号捕获/恢复模块已经开发完成,并按预期工作.当我为模块编写单元测试时,我遇到了一个小麻烦.
My Linux signal catching/resuming module has been developed, and worked as expecting. When I'm coding the unit-test for the module, I encounter a small trouble.
这些是 UT 代码(通过 GTest):
These are the UT codes(by means of GTest):
int do_div_by_0() {
int j = 0;
return 123 / j; /* During release-buidling, this div-op would be optimized out,
although it would be not when debug-building! */
};
TEST_F( SignalsHandling_F, divByZeroDying ) {
ASSERT_EXIT( {
do_div_by_0();
// never should go here!
exit( EXIT_SUCCESS );
}, KilledBySignal( SIGFPE ), "" );
};
如果所有代码都是在调试模式下构建的,那就没有问题.但是在Release模式下除法运算会被优化掉,因此SIGFPE信号永远不会被触发!
If all codes are built in Debug mode, there's no problem. But the division operation would be optimized out in Release mode, as a result the SIGFPE signal would Never be triggered!
为了保持产品代码和测试代码之间的一致性,我必须在发布产品时以发布模式构建它们.
To keep the consistency between product codes and testing codes, I must build them all in release mode when I release my product.
如何编写一段始终触发信号SIGFPE的代码?
How to compose a piece of code that always trigger the signal SIGFPE?
如果更实际",我不想使用 raise() 函数方法存在,因为我想实际触发 SIGFPE 信号.
I don't want to use raise() function if a more "actual" method exists, because I want to actually trigger out SIGFPE signal.
谢谢!请原谅我糟糕的英语!
Thanks! Pls forgive my poor English!
推荐答案
我认为 ChrisDodd 的答案是最准确的.IE.忽略 do_div_by_0 的返回值,以便编译器优化除法运算.
I think that ChrisDodd's answer is the most precise one. I.e. the return value of do_div_by_0 is ignored, so that the compiler optimizes out the division operation.
调用do_div_by_0时需要用到返回值,如下:
We need to use the return value when we call do_div_by_0, like follows:
TEST_F( SignalsHandling_F, divByZeroDying ) {
ASSERT_EXIT( {
std::cerr << do_div_by_0();
// never should go here!
exit( EXIT_SUCCESS );
}, KilledBySignal( SIGFPE ), "" );
};
有效!
谢谢大家!!!
这篇关于如何生成始终触发信号 SIGFPE(div by zero) 的代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!