Windows XP Windows 7 Windows 2003 Windows Vista Windows教程綜合 Linux 系統教程
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟件教程
 Windows教程網 >> Linux系統教程 >> Linux教程 >> 解釋:發生段錯誤時,Linux系統會如何產生core文件

解釋:發生段錯誤時,Linux系統會如何產生core文件

日期:2017/2/7 9:20:48      編輯:Linux教程

 

Linux下的C程序常常會因為內存訪問錯誤等原因造成segment fault(段錯誤),此時如果系統core dump功能是打開的,那麼將會有內存映像轉儲到硬盤上來,之後可以用gdb對core文件進行分析,還原系統發生段錯誤時刻的堆棧情況。這對於我們發現程序bug很有幫助。

使用ulimit -a可以查看系統core文件的大小限制;使用ulimit -c [kbytes]可以設置系統允許生成的core文件大小,例如

ulimit -c 0 不產生core文件

ulimit -c 100 設置core文件最大為100k

ulimit -c unlimited 不限制core文件大小

先看一段會造成段錯誤的程序:

#include

int main()

{

char *ptr="linuxers.cn";

*ptr=0;

}

編譯運行後結果如下:

[leconte@localhost test]$ gcc -g -o test a.c

[leconte@localhost test]$ ./test

段錯誤

此時並沒有產生core文件,接下來使用ulimit -c設置core文件大小為無限制,再執行./test程序,結果如下:

[leconte@localhost ~]$ ulimit -a

core file size (blocks, -c) 0

[leconte@localhost test]$ ulimit -c unlimited

[leconte@localhost test]$ ulimit -a

core file size (blocks, -c) unlimited

[leconte@localhost test]$ ./test

段錯誤 (core dumped)

[leconte@localhost test]$ ls -al core.*

-rw------- 1 leconte leconte 139264 01-06 22:31 core.2065

可見core文件已經生成,接下來可以用gdb分析,查看堆棧情況:

[leconte@localhost test]$ gdb ./test core.2065

GNU gdb Fedora (6.8-27.el5)

Copyright (C) 2008 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 "i386-redhat-linux-gnu"...

warning: exec file is newer than core file.

warning: Can't read pathname for load map: Input/output error.

Reading symbols from /lib/libc.so.6...done.

Loaded symbols for /lib/libc.so.6

Reading symbols from /lib/ld-linux.so.2...done.

Loaded symbols for /lib/ld-linux.so.2

Core was generated by `./test'.

Program terminated with signal 11, Segmentation fault.

[New process 2065]

#0 0x0804836f in main () at a.c:6

6 *ptr=0;

從上述輸出可以清楚的看到,段錯誤出現在a.c的第6行,問題已經清晰地定位到了。

很多系統默認的core文件大小都是0,我們可以通過在shell的啟動腳本/etc/bashrc或者~/.bashrc等地方來加入 ulimit -c 命令來指定core文件大小,從而確保core文件能夠生成。

除此之外,還可以在/proc/sys/kernel/core_pattern裡設置core文件的文件名模板,詳情請看core的官方man手冊。

Copyright © Windows教程網 All Rights Reserved