-1

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.

user129393192
  • 797
  • 1
  • 8
  • The question is how to "dump core" on segfaults. Not raise a segfault @NateEldredge – user129393192 May 29 '23 at 04:59
  • Got it. Thanks @NateEldredge . Not sure why the spec specifically mentions doing this ... I had thought core dumps are OS generated – user129393192 May 29 '23 at 05:02
  • How about an intentional core dump : https://stackoverflow.com/questions/979141/how-to-programmatically-cause-a-core-dump-in-c-c – Aishwarya G M May 29 '23 at 12:00
  • So does any segmentation fault force a core dump then? I’m a bit confused why the project requires separate options `—segfault` and `—core-dump` then – user129393192 May 29 '23 at 17:03

1 Answers1

3

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.

Nate Eldredge
  • 48,811
  • 6
  • 54
  • 82