使用C程序更改应用程序核心转储目录

时间:2019-04-16 06:16:41

标签: c linux

我有一种情况,我想使用c程序更改当前应用程序的核心转储目录。

我有一个选项可以对指定目录执行chdir()。但这会更改应用程序的主目录。而且我正在寻找一些只能更改核心转储目录的API。

1 个答案:

答案 0 :(得分:3)

您可以通过/proc/sys/kernel/core_pattern全局更改核心转储模式。

但是,如果您只想更改一个进程的核心转储目录,则可以执行Apache Web服务器的工作-在核心转储之前注册一个用于更改当前目录的信号处理程序:

#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;
}

请注意,由于这依赖于崩溃的应用程序本身的设置并能够运行信号处理程序,因此它不能做到100%防弹-可能在设置信号处理程序之前就已交付信号,或者信号处理程序本身可能损坏。

相关问题