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
