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

编程入门 行业动态 更新时间:2024-10-27 22:21:59
本文介绍了如何在 Linux 中捕获分段错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要在第三方库清理操作中捕获分段错误.这有时会在我的程序退出之前发生,我无法解决这个问题的真正原因.在 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.

更多推荐

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

本文发布于:2023-10-09 10:22:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1475476.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:错误   如何在   Linux

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!