關於Core文件
Linux程序在運行過程中可能會出現奔潰的現象,此時啓用Core文件可以記錄程序的奔潰現場,方便事後查找問題。
準備工作
- 啓用core文件
默認情況下的core文件是不啓用的,即程序奔潰不會生成奔潰core文件,所以需要開啓這個功能 - 查看core文件狀態
如果core file size行爲0,那麼表示沒有啓用core文件,需要執行ulimit -a
ulimit -c 2048
重置core文件大小的上限,可以自定義文件大小上限值。
- 設定core文件名和保存地址
上述命令表示在當前目錄生成奔潰文件,文件帶了進程ID。還有其他可選的參數:sudo echo "./core.%p" > /proc/sys/kernel /core_pattern
%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
使用core文件
按照之前的設置,當程序奔潰後,會在程序所在目錄生成core文件。此時我們就可以使用gdb打開core文件
gdb 程序名 core文件
一般情況下,程序會直接定位到程序出錯的位置,如果沒有,可以使用where命定來定位。
需要注意,程序編譯時要加上參數選項-g,使得由足夠多的調試信息。