1. 程式人生 > 其它 >ubuntu開啟core dump

ubuntu開啟core dump

ubuntu開啟core dump

1. ubuntu預設core dump是關閉的

通過命令$ ulimit -a檢視:

core file size這一項為0,說明不生成core dump檔案。

2. 開啟方法

通過命令$ ulimit -c unlimited設定生成的core檔案大小不限,也可以按自己的需求設定大小,設定完成後:

但是,這樣設定會有一個問題,就是這個命令只在當前開啟的shell中生效,關閉後就失效了。

3. 每次開啟shell能夠自動開啟

可以在~/.bashrc(只對當前使用者生效)檔案末尾新增ulimit -c unlimited,這樣每次開啟shell都會生效,可以使用編輯器或者輸入命令$ echo 'ulimit -c unlimited' >> ~/.bashrc

進行新增。

4. 測試

原始檔test.cpp

#include <iostream>
using namespace std;

int main() {
    int *p = nullptr;
    *p = 0; // 給空指標指向的地址賦值,引發core dump
    return 0;
}

編譯:$ g++ -g test.cpp -o test(-g新增除錯資訊)
執行:$ ./test
結果:

Segmentation fault (core dumped)

在與原始檔相同目錄下會生成名為core的core dump檔案,使用gdb檢視呼叫棧$ gdb test core

通過gdb可以定位到發生core dump的位置為test.cpp檔案的main()函式,具體在原始檔的第6行,符合預期。

2021.1.11更新:

預設生成的core dump檔案的名稱為core,不夠直觀,可通過以下命令修改:
$ sudo sysctl -w kernel.core_pattern=core.%p.%s.%c.%d.%P.%E
其中每個%開頭的符號含義如下(來自man,命令:man 5 core):

   Naming of core dump files
       By default, a core dump file is named core, but the /proc/sys/kernel/core_pattern file (since  Linux  2.6  and
       2.4.21)  can  be  set  to  define a template that is used to name core dump files.  The template can contain %
       specifiers which are substituted by the following values when a core file is created:

           %%  a single % character
           %c  core file size soft resource limit of crashing process (since Linux 2.6.24)
           %d  dump mode—same as value returned by prctl(2) PR_GET_DUMPABLE (since Linux 3.7)
           %e  executable filename (without path prefix)
           %E  pathname of executable, with slashes ('/') replaced by exclamation marks ('!') (since Linux 3.0).
           %g  (numeric) real GID of dumped process
           %h  hostname (same as nodename returned by uname(2))
           %i  TID of thread that triggered core dump, as seen in the PID  namespace  in  which  the  thread  resides
               (since Linux 3.18)
           %I  TID of thread that triggered core dump, as seen in the initial PID namespace (since Linux 3.18)
           %p  PID of dumped process, as seen in the PID namespace in which the process resides
           %P  PID of dumped process, as seen in the initial PID namespace (since Linux 3.12)
           %s  number of signal causing dump
           %t  time of dump, expressed as seconds since the Epoch, 1970-01-01 00:00:00 +0000 (UTC)
           %u  (numeric) real UID of dumped process

參考:https://stackoverflow.com/questions/17965/how-to-generate-a-core-dump-in-linux-on-a-segmentation-fault