歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux教程 >> Linux程序崩潰時自動生成 Core Dump

Linux程序崩潰時自動生成 Core Dump

日期:2017/2/28 16:20:08   编辑:Linux教程
程序總免不了要崩潰的…… 這是常態,要淡定!

利用 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》去折騰了。當然,這個資源限制的修改僅對當前進程(含子進程)有效。
Copyright © Linux教程網 All Rights Reserved