Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a C program produce a core dump of itself without terminating?

I want a C program to produce a core dump under certain circumstances. This is a program that runs in a production environment and isn't easily stopped and restarted to adjust other kinds of debugging code. Also, since it's in a production environment, I don't want to call abort(). The issues under investigation aren't easily replicated in a non-production environment. What I'd like is for the program, when it detects certain issues, to produce a core dump on its own, preferably with enough information to rename the file, and then continue.

like image 841
Joshua Swink Avatar asked Sep 25 '08 04:09

Joshua Swink


People also ask

How is core dump generated?

A core dump is a file that gets automatically generated by the Linux kernel after a program crashes. This file contains the memory, register values, and the call stack of an application at the point of crashing.

What is core dump in C?

Core Dump/Segmentation fault is a specific kind of error caused by accessing memory that “does not belong to you.” When a piece of code tries to do read and write operation in a read only location in memory or freed block of memory, it is known as core dump. It is an error indicating memory corruption.

Why do core dumps happen?

A core dump or a crash dump is a memory snapshot of a running process. A core dump can be automatically created by the operating system when a fatal or unhandled error (for example, signal or system exception) occurs. Alternatively, a core dump can be forced by means of system-provided command-line utilities.

Where is core dump generated?

By default, core dumps are sent to systemd-coredump which can be configured in /etc/systemd/coredump. conf . By default, all core dumps are stored in /var/lib/systemd/coredump (due to Storage=external ) and they are compressed with zstd (due to Compress=yes ).


2 Answers

void create_dump(void) {     if(!fork()) {         // Crash the app in your favorite way here         *((void*)0) = 42;     } } 

Fork the process then crash the child - it'll give you a snapshot whenever you want

like image 108
Ana Betts Avatar answered Oct 06 '22 01:10

Ana Betts


Another way might be to use the Google Coredumper library. This creates a similar result to the fork+abort technique but plays nicer with multithreaded apps (suspends all threads for a little while before forking so that they don't make a mess in the child).

Example:

     #include <google/coredumper.h>     ...     WriteCoreDump('core.myprogram');     /* Keep going, we generated a core file,      * but we didn't crash.      */ 
like image 45
regnarg Avatar answered Oct 05 '22 23:10

regnarg