1. 程式人生 > 其它 >linux中core dump開啟使用教程

linux中core dump開啟使用教程

一、什麼是coredump

我們經常聽到大家說到程式core掉了,需要定位解決,這裡說的大部分是指對應程式由於各種異常或者bug導致在執行過程中異常退出或者中止,並且在滿足一定條件下(這裡為什麼說需要滿足一定的條件呢?下面會分析)會產生一個叫做core的檔案。

通常情況下,core檔案會包含了程式執行時的記憶體,暫存器狀態,堆疊指標,記憶體管理資訊還有各種函式呼叫堆疊資訊等,我們可以理解為是程式工作當前狀態儲存生成第一個檔案,許多的程式出錯的時候都會產生一個core檔案,通過工具分析這個檔案,我們可以定位到程式異常退出的時候對應的堆疊呼叫等資訊,找出問題所在並進行及時解決。

二、cored dump開啟

1、暫時生效
ulimit -c unlimited

2、永久生效
修改/etc/security/limits.conf

  • soft core unlimited
  • hard core unlimited

3、永久生效
修改/etc/profile

ulimit -c unlimited

三、設定core檔案的名稱和檔案路徑
預設生成路徑:輸入可執行檔案執行命令的同一路徑下
預設生成名字:預設命名為core。新的core檔案會覆蓋舊的core檔案

a.設定pid作為副檔名

1:新增pid作為副檔名,生成的core檔名稱為core.pid
0:不新增pid作為副檔名,生成的core檔名稱為core
修改 /proc/sys/kernel/core_uses_pid 檔案內容為: 1
修改檔案命令:

echo "1" > /proc/sys/kernel/core_uses_pid
或者
sysctl -w kernel.core_uses_pid=1 kernel.core_uses_pid = 1

b. 控制core檔案儲存位置和檔名格式

修改檔案命令: echo "/corefile/core-%e-%p-%t" > /proc/sys/kernel/core_pattern
或者:
sysctl -w kernel.core_pattern=/corefile/core.%e.%p.%s.%E
可以將core檔案統一生成到/corefile目錄下,產生的檔名為core-命令名-pid-時間戳
以下是引數列表:
%p - insert pid into filename 新增pid(程序id)
%u - insert current uid into filename 添加當前uid(使用者id)
%g - insert current gid into filename 添加當前gid(使用者組id)
%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 新增導致產生core的命令名

3.測試是否能生成core檔案
kill -s SIGSEGV $$
檢視/corefile目錄下是否生成了core檔案

如果是需要測試go程式是否能生成core檔案,需要設定環境變數GOTRACEBACK=crash

4.除錯core檔案
Eg. test.c

include<stdio.h>

int main()
{
int *p = NULL;
*p = 0;
return 0;
}
root@ubuntu:~# gcc -o test test.c
root@ubuntu:~# ./test
Segmentation fault (core dumped)
bingo:這裡出現段錯誤並生成core檔案了
在/corefile目錄下發現core-test-31421-1476266571
開始除錯
gdb ./test core-test-31421-1476266571

根據堆疊資訊檢視bug

  1. 基本GDB命令
    為了定位問題,常常需要進行單步跟蹤,設定斷點之類的操作。

下邊列出了GDB一些常用的操作。

啟動程式:run
設定斷點:b 行號|函式名
刪除斷點:delete 斷點編號
禁用斷點:disable 斷點編號
啟用斷點:enable 斷點編號
單步跟蹤:next (簡寫 n)
單步跟蹤:step (簡寫 s)
列印變數:print 變數名字 (簡寫p)
設定變數:set var=value
檢視變數型別:ptype var
順序執行到結束:cont
順序執行到某一行: util lineno
列印堆疊資訊:bt