使用GDB分析core dump文件

首先需要对环境进行配置,即配置core文件的输出:
运行命令:ulimit -c unlimited 
该命令用于设置core文件大小不限制
修改/etc/sysctl.conf文件,在文件末尾添加下面一行
kernel.core_pattern=/tmp/core-%e
并修改kernel.core_uses_pid = 1 为
kernel.core_uses_pid = 0 这样core文件的格式就是
core-可执行文件的名字,这里我把进程号去掉了,觉得进程号在此处没多大用处。文件所在目录为/tmp下,也可以自己修改为可执行文件所在目录,这样比较直观。
然后运行命令:sysctl -p /etc/sysctl.conf

假设将其值改变为:"/home/duanbei/corefile/core-%e-%p-%t", 那么所有的core文件将保存在"/home/duanbei/corefile"目录下,文件名格式为“core-程序名-pid-时间戳”

格式参数列表

[plain] view plaincopyprint?
%p - insert pid into filename 
%u - insert current uid into filename 
%g - insert current gid into filename 
%s - insert signal that caused the coredump into the filename 
%t - insert UNIX time that the coredump occurred into filename 
%h - insert hostname where the coredump happened into filename 
%e - insert coredumping executable name into filename 
%p - insert pid into filename
%u - insert current uid into filename
%g - insert current gid into filename
%s - insert signal that caused the coredump into the filename
%t - insert UNIX time that the coredump occurred into filename
%h - insert hostname where the coredump happened into filename
%e - insert coredumping executable name into filename
注:如果设置了“%p”,而“/proc/sys/kernel/core_uses_pid”值又为1,则不会添加PID后缀,因文件名中已含该信息


到此配置工作完成,下面对core文件进行分析。
比如我们运行的代码出现段错误,如下:
[root@localhost mywork]# ./testGdb
Segmentation fault (core dumped)
[root@localhost mywork]#
[root@localhost mywork]# gdb testGdb core-testGdb

GNU gdb (GDB) Fedora (7.0-3.fc12)
Copyright (C) 2009 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "i686-redhat-linux-gnu".
For bug reporting instructions, please see:
...
Reading symbols from /home/mywork/testGdb...done.

warning: .dynamic section for "/lib/libc.so.6" is not at the expected address

warning: difference appears to be caused by prelink, adjusting expectations
Reading symbols from /lib/libc.so.6...(no debugging symbols found)...done.
Loaded symbols for /lib/libc.so.6
Reading symbols from /lib/ld-linux.so.2...(no debugging symbols found)...done.
Loaded symbols for /lib/ld-linux.so.2
Core was generated by `./testGdb'.
Program terminated with signal 11, Segmentation fault.//显示出了程序崩溃的原因如下
#0  0x0804839a in copy (t=0x0) at testGdb.c:5
5        *t = 10;
Missing separate debuginfos, use: debuginfo-install glibc-2.11-2.i686
(gdb) bt //显示函数调用堆栈,显然是main函数调用copy函数
#0  0x0804839a in copy (t=0x0) at testGdb.c:5
#1  0x080483b0 in main () at testGdb.c:11
(gdb) f 1 //打印栈号为1的堆栈,显示main函数是怎么调用copy函数,f的全名为frame
#1  0x080483b0 in main () at testGdb.c:11
11        copy(s);
(gdb) p s  //打印变量的值
$1 = 0x0

你可能感兴趣的:(linux应用)