Linux中捕获SIGSEGV中断

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

/*void log2file(char *fmt, ...)
{
    time_t t = time(NULL);
    if(access("./log", F_OK) != 0)
        if(mkdir("./log", 0755) == -1)  
        {
            perror("mkdir ./log failed");
            return;
        }
    char temps[500];
    strftime(temps, sizeof(temps) - 1, "./log/%Y%m%d.log", localtime(&t));     //年-月-日 时-分-秒
    
    FILE * fp = fopen(temps, "a");
    strftime(temps, sizeof(temps) - 1, "%Y-%m-%d %H:%M:%S.%u ", localtime(&t));     //年-月-日 时-分-秒
    fputs(temps, fp);
    va_list args;
    va_start(args,fmt);
    (void)vfprintf(fp, fmt, args);
    (void)vfprintf(stdout, fmt, args);
    va_end(args);
    fclose(fp);
}*/

#define SIZE 1000
void *trace_buffer[SIZE];  
void fault_trap(int n, siginfo_t *info, void *myact)  
{  
        int i, num;
        char **calls;  
        log2file("Fault address:%X\n",info->si_addr);     
        num = backtrace(trace_buffer, SIZE);  
        calls = backtrace_symbols(trace_buffer, num);  
        for (i = 0; i < num; i++)  
                printf("%s\n", calls[i]);  
        exit(1);  
}


void setuptrap()  
{  
    struct sigaction act;  
    sigemptyset(&act.sa_mask);     
    act.sa_flags=SA_SIGINFO;      
    act.sa_sigaction=fault_trap;  
    sigaction(SIGSEGV,&act,NULL);  
}

int main(){
    setuptrap();
    while(1);
}

 

你可能感兴趣的:(Linux)