转载:http://blog.csdn.net/hanchaoman/article/details/5583457
在SIGSEGV的handler中调用gdb,
命令gdb [exec file] [pid]可以让gdb附加到这个进程上
#include <limits.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <signal.h> #include <stdlib.h> //获取进程名 size_t get_executable_path( char* processdir,char* processname, size_t len) { char* path_end; if(readlink("/proc/self/exe", processdir,len) <=0) return -1; path_end = strrchr(processdir, '/'); if(path_end == NULL) return -1; ++path_end; strcpy(processname, path_end); *path_end = '\0'; return (size_t)(path_end - processdir); } void dump(int signo) { char path[PATH_MAX]; char processname[1024]; char cmd[1024]; bzero(path, PATH_MAX); bzero(processname, 1024); bzero(cmd, 1024); get_executable_path( path, processname, sizeof(path)); snprintf(cmd, sizeof(cmd), "gdb %s %d", processname, getpid()); printf("%s\n", cmd); system(cmd); exit(0); } void test_function (void) { unsigned char *ptr = 0x00; *ptr = 0x00; } int main (void) { signal(SIGSEGV, &dump); test_function(); return 0; }