1.什麼是core文件?
有問題的程序運行後,產生“段錯誤 (核心已轉儲)”時生成的具有堆棧信息和調試信息的文件。
編譯時需要加 -g 選項使程序生成調試信息: gcc -g core_test.c -o core_test
2.怎樣配置生成 core 文件
(1)core文件開關
①使用 ulimit -c 查看core開關,如果爲0表示關閉,不會生成core文件;
②使用 ulimit -c [filesize] 設置core文件大小,當最小設置爲4之後纔會生成core文件;
③使用 ulimit -c unlimited 設置core文件大小爲不限制,這是常用的做法;
④如果需要開機就執行,則需要將這句命令寫到 /etc/profile 等文件。
(2)core文件命名和保存路徑
①core文件有默認的名稱和路徑,但爲了方便,我們通常會自己命名和指定保存路徑;
②可以通過 /proc/sys/kernel/core_pattern 設置 core 文件名和保存路徑,方法如下:
%p - insert pid into filename 添加pidecho "/corefile/core-%e-%p-%t" > /proc/sys/kernel/core_pattern
命名的參數列表:
%u - insert current uid into filename 添加當前uid
%g - insert current gid into filename 添加當前gid
%s - insert signal that caused the coredump into the filename 添加導致產生core的信號
%t - insert UNIX time that the coredump occurred into filename 添加core文件生成時的unix時間
%h - insert hostname where the coredump happened into filename 添加主機名
%e - insert coredumping executable name into filename 添加命令名。
3.調試core文件
(1)方法1: gdb [exec file] [core file] 然後執行bt看堆棧信息:
(2)方法②:gdb -c [core file],然後 file [exec file],最後再使用 bt 查看錯誤位置: