在Linux下產生並除錯core檔案

luckythc發表於2008-04-03

$ uname -a

$ vi foo.c

$ gcc -Wall -g foo.c

$ ./a.out

$ ls -l core.*

$ ulimit -c 1024

$ ulimit -a

$ ./a.out

$ ls -l core.*

$ gdb --core=core.9128

(gdb) file ./a.out

(gdb) l

[@more@]

先看看我用的是個什麼機器:

$ uname -a
Linux dev 2.4.21-9.30AXsmp #1 SMP Wed May 26 23:37:09 EDT 2004 i686 i686 i386 GNU/Linux

再看看預設的一些引數,注意core file size是個0,程式出錯時不會產生core檔案了。

$ ulimit -a
core file size (blocks, -c) 0
data seg size (kbytes, -d) unlimited
file size (blocks, -f) unlimited
max locked memory (kbytes, -l) 4
max memory size (kbytes, -m) unlimited
open files (-n) 2048
pipe size (512 bytes, -p) 8
stack size (kbytes, -s) 10240
cpu time (seconds, -t) unlimited
max user processes (-u) 7168
virtual memory (kbytes, -v) unlimited

寫個簡單的程式,看看core檔案是不是會被產生。

$ more foo.c

#include

static void sub(void);

int main(void)
{
sub();
return 0;
}

static void sub(void)
{
int *p = NULL;

/* derefernce a null pointer, expect core dump. */
printf("%d", *p);
}

$ gcc -Wall -g foo.c
$ ./a.out
Segmentation fault

$ ls -l core.*
ls: core.*: No such file or directory

沒有找到core檔案,我們改改ulimit的設定,讓它產生。1024是隨便取的,要是core檔案大於1024個塊,就產生不出來了。

$ ulimit -c 1024

$ ulimit -a
core file size (blocks, -c) 1024
data seg size (kbytes, -d) unlimited
file size (blocks, -f) unlimited
max locked memory (kbytes, -l) 4
max memory size (kbytes, -m) unlimited
open files (-n) 2048
pipe size (512 bytes, -p) 8
stack size (kbytes, -s) 10240
cpu time (seconds, -t) unlimited
max user processes (-u) 7168
virtual memory (kbytes, -v) unlimited

$ ./a.out
Segmentation fault (core dumped)
$ ls -l core.*
-rw------- 1 uniware uniware 53248 Jun 30 17:10 core.9128

注意看上述的輸出資訊,多了個(core dumped)。確實產生了一個core檔案,9128是該程式的PID。我們用GDB來看看這個core。

$ gdb --core=core.9128
GNU gdb Asianux (6.0post-0.20040223.17.1AX)
Copyright 2004 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB. Type "show warranty" for details.
This GDB was configured as "i386-asianux-linux-gnu".
Core was generated by `./a.out'.
Program terminated with signal 11, Segmentation fault.
#0 0x08048373 in ?? ()
(gdb) bt
#0 0x08048373 in ?? ()
#1 0xbfffd8f8 in ?? ()
#2 0x0804839e in ?? ()
#3 0xb74cc6b3 in ?? ()
#4 0x00000000 in ?? ()

此時用bt看不到backtrace,也就是呼叫堆疊,原來GDB還不知道符號資訊在哪裡。我們告訴它一下:

(gdb) file ./a.out
Reading symbols from ./a.out...done.
Using host libthread_db library "/lib/tls/libthread_db.so.1".
(gdb) bt
#0 0x08048373 in sub () at foo.c:17
#1 0x08048359 in main () at foo.c:8

此時backtrace出來了。

(gdb) l
8 sub();
9 return 0;
10 }
11
12 static void sub(void)
13 {
14 int *p = NULL;
15
16 /* derefernce a null pointer, expect core dump. */
17 printf("%d", *p);
(gdb)

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/793819/viewspace-1001871/,如需轉載,請註明出處,否則將追究法律責任。

相關文章