在分段错误时转储核心

huangapple go评论64阅读模式
英文:

Dumping core on segmentation faults

问题

我正在编写一个C程序(作为练习),其中可以通过选项--segfault来指定程序触发段错误。另外,我还要有一个选项--dump-core,在段错误时会将核心转储。我无法找到关于如何通过C强制进行核心转储的信息。如何实现这一点?

我希望它可以在MacOS和Linux上运行。

英文:

I am writing a C program (as an exercise), where you can specify the program to segfault with an option --segfault. Additionally, I am to have an option --dump-core where you dump core on segmentation faults. I've been unable to find information on how to force a core dump via C. How can one do this?

I'd like it to port to MacOS and Linux.

答案1

得分: 3

关于在段错误时程序是否会转储核心,实际上并不应该由程序本身决定,而应由用户和/或系统管理员决定。所以在我看来,这不是一个程序应该提供的明智选项。

尽管如此,控制是否生成核心转储的最常见方法是通过核心文件大小的资源限制(rlimit)。如果设置为零,将不会生成核心转储。通常用户会在其shell中使用ulimit -c XXX或类似的方式来设置这个值。但是,您的程序也可以尝试使用setrlimit(2)系统调用来设置它。例如,您可以执行以下操作:

struct rlimit r;
getrlimit(RLIMIT_CORE, &r);
r.rlim_cur = r.rlim_max;
setrlimit(RLIMIT_CORE, &r);

以将限制设置为其最大允许值。但是,最大允许值可能是0(由您的进程的某个祖先设置),在这种情况下,您无法增加它。

还有其他可能会影响是否可能生成核心转储的系统设置,您可能没有足够的权限来修改这些设置。Linux的core(5)手册页解释了必要的条件。

英文:

[tag:linux]

Whether a program dumps core on segfault is not really supposed to be left up to the program itself, but rather up to the user and/or sysadmin. So in my opinion, this isn't really a sensible option for a program to provide.

Having said that, the most common way to control whether a core dump is produced is via the rlimit for core file size. If it is zero, no core dumps are produced. Normally the user would set this with ulimit -c XXX or equivalent in their shell. However your program can also attempt to set it with the setrlimit(2) system call. For instance you might do

struct rlimit r;
getrlimit(RLIMIT_CORE, &r);
r.rlim_cur = r.rlim_max;
setrlimit(RLIMIT_CORE, &r);

to set the limit equal to its maximum allowed value. However, that maximum allowed value might be 0 (set by some ancestor of your process) in which case you cannot increase it.

There are other system settings that might affect whether core dumps are possible, which you may or may not have enough privileges to modify. The Linux core(5) man page explains the necessary conditions.

huangapple
  • 本文由 发表于 2023年5月29日 12:56:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76354765.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定