避免中止在libgmp [英] avoiding abort in libgmp
问题描述
我有一个使用libgmp一些code。在一些点,用户可要求一个非常大的数量的阶乘。不幸的是,这导致libgmp提高异常中止信号
I have some code that uses libgmp. At some point the user may request a factorial of a very large number. Unfortunately, this results in libgmp raising an abort signal.
例如下面的code:
#include <cmath>
#include <gmp.h>
#include <iostream>
int main() {
mpz_t result;
mpz_init(result);
mpz_fac_ui(result, 20922789888000);
std::cout << mpz_get_si(result) << std::endl;
}
结果:
$ ./test
gmp: overflow in mpz type
Aborted
显然,所产生的数量是非常大的。反正有超过中止更加妥善地处理错误。这是一个基于GUI应用程序,它是中止pretty多少来处理这类问题的最不可取的方法。
Apparently, the number produced is REALLY big. Is there anyway to handle the error more gracefully than an abort. This is a GUI based application and it aborting is pretty much the least desirable way to handle this sort of issue.
推荐答案
优雅地在应用程序中处理这些错误,最好的办法可能是叉掉一个辅助程序来执行GMP计算。如果辅助过程是由 SIGABRT
终止,你的父进程可以检测到并报告错误给用户。
The best way to handle these errors gracefully in your application is probably to fork off a helper process to perform the GMP calculations. If the helper process is killed by SIGABRT
, your parent process can detect that and report an error to the user.
的(下面是我原来的答复,其中有按GMP文档不确定的结果 - 这是离开这里的完整性)。的
如果您安装了 SIGABRT
使用的longjmp()
信号处理程序可以捕获的错误p>
You can catch the error if you install a signal handler for SIGABRT
that uses longjmp()
:
jmp_buf abort_jb;
void abort_handler(int x)
{
longjmp(abort_jb, 1);
}
int dofac(unsigned long n)
{
signal(SIGABRT, abort_handler);
if (setjmp(abort_jb))
goto error;
mpz_t result;
mpz_init(result);
mpz_fac_ui(result, 20922789888000);
std::cout << mpz_get_si(result) << std::endl;
signal(SIGABRT, SIG_DFL);
return 0;
error:
signal(SIGABRT, SIG_DFL);
std::cerr << "Caught SIGABRT from GMP.\n";
return 1;
}
这篇关于避免中止在libgmp的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!