Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Linux 下 core dump 的開啟方式:用 getrlimit/setrlimit 實測

程式在 Linux 上遇到段錯誤時,預設不一定會留下 core 檔——能不能產生,取決於 RLIMIT_CORE 的設定。因此除錯前,第一件事是先把限制解除。以下這段程式示範如何在程式內部自行調整 rlimit,然後故意觸發一次段錯誤來驗證。

#include <stdio.h>

// 產生 core 檔的設定函式
int SetRLimit()
{
#ifdef WIN32
#else
    struct rlimit tRLimit;
    int iRtn = 0;
    printf("SetRLimit ...\n");

    iRtn = getrlimit(RLIMIT_CORE, &tRLimit);
    if (0 == iRtn)
    {
        printf("getrlimit corefile size limit_cur = %d, max = %d\n",
               tRLimit.rlim_cur, tRLimit.rlim_max);
        tRLimit.rlim_max = tRLimit.rlim_cur = RLIM_INFINITY;
        iRtn = setrlimit(RLIMIT_CORE, &tRLimit);
        printf("setrlimit corefile size limit:cur = %d, return %d\n",
               tRLimit.rlim_cur, iRtn);
    }

    iRtn = getrlimit(RLIMIT_NOFILE, &tRLimit);
    if (0 == iRtn)
    {
        printf("getrlimit number of files limit : cur = %d, max = %d\n",
               tRLimit.rlim_cur, tRLimit.rlim_max);
        tRLimit.rlim_cur = 10000;
        iRtn = setrlimit(RLIMIT_NOFILE, &tRLimit);
        printf("setrlimit number of files limit : cur = %d, return %d\n",
               tRLimit.rlim_cur, iRtn);
    }
#endif
    return 0;
}

int main()
{
    unsigned char *ptr = 0x00;
    SetRLimit();
    *ptr = 0x00;      // 故意觸發段錯誤,用來測試 core 檔是否產生
    return 0;
}

幾個實務提醒

  • 除了程式內呼叫 setrlimit,也可以在 shell 下指令 ulimit -c unlimited,通常這樣做更省事。
  • core 檔的落點與檔名由 /proc/sys/kernel/core_pattern 決定;若被 systemd 接管,檔案可能進到 coredumpctl 而非當前目錄。
  • 上述程式碼中 struct rlimt 是原文的拼字錯誤,正確名稱為 struct rlimit;另外 rlim_cur 的型別是 rlim_t,用 %d 列印在 64 位元系統上並不安全,正式使用前請調整格式字串。
  • 要讓 RLIM_INFINITY 生效,通常需要相應的權限,一般使用者只能把上限提高到目前的軟限以內。

拿到 core 檔之後,用 gdb ./your_program core 載入,再下 bt 就能回溯崩潰時的呼叫堆疊。

Copyright © Linux教程網 All Rights Reserved