程序异常终止时,将会产生core文件,其包含了程序崩溃时的信息,比如调用栈等,可使用gdb来调试core文件。
实例:主函数创建一个子线程,子线程内部未正确使用指针,引发Segmentation fault (core dumped)
x
void* running(void* arg){ printf("At child thread: %ld\n", pthread_self()); int *tmp; *tmp = 1; //引发段错误}int main(){ printf("At parent thread: %ld\n", pthread_self());
pthread_t tid; int ret = pthread_create(&tid, NULL, running, NULL); if(ret != 0) { return -1; } pthread_join(tid, NULL); return 0;}
x
# 编译:需要加-gxxx# gcc -g main.c -lpthreadxxx# ./a.outAt parent thread: 140656779855680At child thread: 140656779851328Segmentation fault (core dumped) # 产生段错误xxx# lsa.out core-a.out-348574-1731476560-11 main.c # 生成了core文件
# gdb调试xxx# gdb a.out core-a.out-348574-1731476560-11...For help, type "help".Type "apropos word" to search for commands related to "word"...Reading symbols from a.out...[New LWP 348575][New LWP 348574][Thread debugging using libthread_db enabled]Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".Core was generated by `./a.out'.Program terminated with signal SIGSEGV, Segmentation fault.#0 0x00005647e54711f9 in running (arg=0x0) at main.c:12 ####找到程序崩溃处12 *tmp = 1; //引发段错误 [Current thread is 1 (Thread 0x7fed3565f640 (LWP 348575))]
# 查看段错误前后文(gdb) l main.c:1278 void* running(void* arg)9 {10 printf("At child thread: %ld\n", pthread_self());11 int *tmp;12 *tmp = 1;13 }14 int main()15 {16 printf("At parent thread: %ld\n", pthread_self());
#查看栈(gdb) bt#0 0x00005647e54711f9 in running (arg=0x0) at main.c:12#1 0x00007fed356f7ac3 in start_thread (arg=<optimized out>) at ./nptl/pthread_create.c:442#2 0x00007fed35789850 in clone3 () at ../sysdeps/unix/sysv/linux/x86_64/clone3.S:81
# 查看局部变量(gdb) info localstmp = 0x0
# 查看参数(gdb) info argsarg = 0x0
# 查看线程(gdb) info threads Id Target Id Frame* 1 Thread 0x7fed3565f640 (LWP 348575) 0x00005647e54711f9 in running (arg=0x0) at main.c:12 2 Thread 0x7fed35660740 (LWP 348574) 0x00007fed357487f8 in __GI___clock_nanosleep (clock_id=clock_id@entry=0, flags=flags@entry=0, req=req@entry=0x7fff7a2a22e0, rem=rem@entry=0x7fff7a2a22e0) at ../sysdeps/unix/sysv/linux/clock_nanosleep.c:78(gdb)
大小:默认情况下,core核心转储文件文件生成大小为0,表示核心转储功能被禁用。
x
# 临时生成大小为无限制xxx# ulimit -c unlimitedxxx# ulimit -cunlimited
# 临时生成位置,说明:# %e: 程序文件的完整路径# %p: 进程ID# %t: 进程崩溃的时间戳# %s: 哪个信号让程序崩溃xxx# echo "/root/coredoc/core-%e-%p-%t-%s" > /proc/sys/kernel/core_patternxxx# cat /proc/sys/kernel/core_pattern/root/coredoc/core-%e-%p-%t-%s