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

用c程序更改应用程序核心转储目录,c,linux,C,Linux,我有一个场景,我想通过当前应用程序使用c程序更改核心转储的目录 我有一个选项可以对指定的目录执行chdir()。但这会更改应用程序的主目录。我正在寻找一些只能更改核心转储目录的API。您可以通过/proc/sys/kernel/core\u pattern全局更改核心转储模式 但是,如果您只想更改一个进程的核心转储目录,则可以执行Apache web server所做的操作—在核心转储之前注册一个更改当前目录的信号处理程序: #include <stdlib.h> #include

我有一个场景,我想通过当前应用程序使用c程序更改核心转储的目录


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

您可以通过
/proc/sys/kernel/core\u pattern
全局更改核心转储模式

但是,如果您只想更改一个进程的核心转储目录,则可以执行Apache web server所做的操作—在核心转储之前注册一个更改当前目录的信号处理程序:

#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;
}
#包括
#包括
#包括
#包括
#包括
#包括
#定义COREDUMP_DIR“/tmp”
静态无效信号(int sig)
{
struct-sigaction-sa;
//更改到我们希望转储核心的目录
chdir(COREDUMP_DIR);
//清除该信号的信号处理程序
memset(&sa,0,sizeof(sa));
sa.sa_handler=SIG_DFL;
sigemptyset(和sa.sa_面具);
sigaction(sig,&sa,NULL);
//再发一次信号
提高(sig);
}
int main(int argc,字符**argv)
{
struct-sigaction-sa;
//为所有需要的信号设置信号处理程序
//可能导致堆芯转储
memset(&sa,0,sizeof(sa));
sa.sa_handler=sig_coredump;
sigemptyset(和sa.sa_面具);
sigaction(SIGSEGV,&sa,NULL);
sigaction(SIGBUS和sa,空);
sigaction(SIGABRT和sa,空);
sigaction(SIGILL,&sa,NULL);
sigaction(SIGFPE和sa,空);
//启用核心转储
结构限制核心限制;
core_limit.rlim_cur=rlim_无穷大;
core_limit.rlim_max=rlim_无穷大;
如果(设置限制(限制核心和核心限制)=-1){
perror(“setrlimit”);
}
//触发堆芯转储
升起(SIGSEGV);
返回0;
}

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

这可能会失败,具体取决于导致分段错误的损坏程度。信号处理可能不再有效。