Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux 核心傾印 產生機制:ulimit 控制 core 檔案大小、gdb 分析段錯誤堆疊

編輯:Linux 教學

C 程式發生 Segmentation fault 時,若啟用 core dump,核心會將記憶體映像寫入磁碟供事後除錯。

啟用與大小控制

ulimit -a                 # 查看目前限制 (core file size 通常為 0)
ulimit -c 0               # 禁止產生 core
ulimit -c 100             # 限制 100 KB
ulimit -c unlimited       # 無限制 (建議開發環境啟用)

永久生效:將 ulimit -c unlimited 加入 /etc/bashrc 或 ~/.bashrc。

檔案命名模板

可透過 /proc/sys/kernel/core_pattern 自訂 core 檔名格式 (如 core.%e.%p.%t),詳見 man 5 core。

實戰範例

// a.c
#include <stdio.h>
int main() {
    char *ptr = "linuxers.cn";
    *ptr = 0;               // 寫入唯讀區段 → Segfault
}
$ gcc -g -o test a.c
$ ./test
段錯誤
$ ulimit -c unlimited
$ ./test
段錯誤 (core dumped)
$ ls -l core.*
-rw------- 1 user user 139264 ... core.2065

gdb 分析堆疊

$ gdb ./test core.2065
...
Core was generated by `./test'.
Program terminated with signal 11, Segmentation fault.
#0  0x0804836f in main () at a.c:6
6       *ptr = 0;

精確定位到第 6 行寫入字串常數區導致錯誤。核心傾印是開發階段定位記憶體錯誤的利器。

Copyright © Windows教程網 All Rights Reserved