Linux程序崩溃时自动生成 Core Dump


程序总免不了要崩溃的…… 这是常态,要淡定! [sweat] 

利用 setrlimit() 函数我们可以将 "core file size" 设置成一个非 0 值,这样就可以在崩溃时自动生成 core 文件了。(可参考 bshell ulimit 命令)
#include <sys/resource.h>  void test() {     char* s = "abc";     *s = 'x'; }  int main(int argc, char** argv) {     struct rlimit res = { .rlim_cur = RLIM_INFINITY, .rlim_max = RLIM_INFINITY };     setrlimit(RLIMIT_CORE, &res);      test();      return (EXIT_SUCCESS); }

很显然,我们在 test() 函数中特意制造了一个 "  Segmentation fault",执行一下看看效果。

$ ./test
Segmentation fault (core dumped)

$ ls -l
total 104 -rw------- 1 yuhen yuhen 172032 2010-01-14 20:59 core -rwxr-xr-x 1 yuhen yuhen   9918 2010-01-14 20:53 test

很好,拿到 core 文件以后就可以参照 《Core Dump》去折腾了。当然,这个资源限制的修改仅对当前进程(含子进程)有效。

相关内容