core保证日志写入
创建:2025-04-27 23:54
更新:2025-04-27 23:54
#include <signal.h>
#include <syslog.h>
#include <unistd.h>
#include <stdlib.h>

void handle_core_signal(int sig, siginfo_t* info, void* context) {
    static int happened = 0;
    if (!happened) { // 避免递归core
        happened = 1;
        // 这里可以处理遇到core时的处理函数,例如日志下发,等等逻辑
        printf("出现错误\n");
    }

    // 恢复默认信号处理
    struct sigaction sa;
    sa.sa_handler = SIG_DFL;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0;
    sigaction(sig, &sa, 0);
    // 重新触发信号(生成核心文件)
    kill(getpid(), sig);
}

int main() {
    // 设置信号处理
    struct sigaction sa;
    sa.sa_sigaction = handle_core_signal;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = SA_SIGINFO;
    sigaction(SIGSEGV, &sa, 0);  // 段错误
    sigaction(SIGABRT, &sa, 0);  // 中止信号
    sigaction(SIGFPE,  &sa, 0);  // 浮点异常

    // 模拟触发段错误(解引用空指针)
    int* ptr = 0;
    *ptr = 42;  // 这里会触发SIGSEGV

    return 0;
}