I have one scenario where I want to change directory for core dumps by current application using c program.
I have one option to do chdir() to specified directory. But this changes the home directory of application. And I am looking for some APIs which can change directory for core dumps only.
Advertisement
Answer
You can change core dump pattern globally through /proc/sys/kernel/core_pattern
.
But if you only want to change the core dump directory of one process, you can do what Apache web server does – register a signal handler that changes the current directory right before core dumping:
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <signal.h> #include <sys/resource.h> #define COREDUMP_DIR "/tmp" static void sig_coredump (int sig) { struct sigaction sa; // Change to the directory we want the core to be dumped chdir (COREDUMP_DIR); // Clear the signal handler for the signal memset (&sa, 0, sizeof (sa)); sa.sa_handler = SIG_DFL; sigemptyset (&sa.sa_mask); sigaction (sig, &sa, NULL); // Send the signal again raise (sig); } int main (int argc, char **argv) { struct sigaction sa; // Set up the signal handler for all signals that // can cause the core dump memset (&sa, 0, sizeof (sa)); sa.sa_handler = sig_coredump; sigemptyset (&sa.sa_mask); sigaction (SIGSEGV, &sa, NULL); sigaction (SIGBUS, &sa, NULL); sigaction (SIGABRT, &sa, NULL); sigaction (SIGILL, &sa, NULL); sigaction (SIGFPE, &sa, NULL); // Enable core dump struct rlimit core_limit; core_limit.rlim_cur = RLIM_INFINITY; core_limit.rlim_max = RLIM_INFINITY; if (setrlimit (RLIMIT_CORE, &core_limit) == -1) { perror ("setrlimit"); } // Trigger core dump raise (SIGSEGV); return 0; }
Note that as this relies on the crashing application itself setting up and being able to run the signal handler, it can’t be 100% bullet-proof – signal may be delivered before signal handler is set up or signal handling itself may get corrupted.