如何在 Linux 中捕获分段错误?

2022-01-12 00:00:00 segmentation-fault try-catch c++

我需要在第三方库清理操作中捕获分段错误.这有时会在我的程序退出之前发生,我无法解决这个问题的真正原因.在 Windows 编程中,我可以使用 __try - __catch 来做到这一点.是否有跨平台或特定于平台的方式来做同样的事情?我在 Linux 中需要这个,gcc.

I need to catch segmentation fault in third party library cleanup operations. This happens sometimes just before my program exits, and I cannot fix the real reason of this. In Windows programming I could do this with __try - __catch. Is there cross-platform or platform-specific way to do the same? I need this in Linux, gcc.

推荐答案

在 Linux 上,我们也可以将这些作为例外.

On Linux we can have these as exceptions, too.

通常,当您的程序执行分段错误时,会发送一个 SIGSEGV 信号.您可以为此信号设置自己的处理程序并减轻后果.当然,您应该真正确定自己可以从这种情况中恢复过来.在你的情况下,我认为你应该调试你的代码.

Normally, when your program performs a segmentation fault, it is sent a SIGSEGV signal. You can set up your own handler for this signal and mitigate the consequences. Of course you should really be sure that you can recover from the situation. In your case, I think, you should debug your code instead.

回到主题.我最近遇到了一个库 (简短手册) 将此类信号转换为异常,因此您可以编写如下代码:

Back to the topic. I recently encountered a library (short manual) that transforms such signals to exceptions, so you can write code like this:

try
{
    *(int*) 0 = 0;
}
catch (std::exception& e)
{
    std::cerr << "Exception caught : " << e.what() << std::endl;
}

不过没有检查.在我的 x86-64 Gentoo 盒子上工作.它有一个特定于平台的后端(借用自 gcc 的 java 实现),因此它可以在许多平台上工作.它仅支持开箱即用的 x86 和 x86-64,但您可以从位于 gcc 源中的 libjava 获取后端.

Didn't check it, though. Works on my x86-64 Gentoo box. It has a platform-specific backend (borrowed from gcc's java implementation), so it can work on many platforms. It just supports x86 and x86-64 out of the box, but you can get backends from libjava, which resides in gcc sources.

相关文章