簡體   English   中英

如何從 C++ 上的分段錯誤中恢復?

[英]How to recover from segmentation fault on C++?

我有一些必須繼續運行的生產關鍵代碼。

將代碼視為

while (true){
   init();
   do_important_things();  //segfault here
   clean();
}

我不能相信代碼沒有錯誤,我需要能夠記錄問題以便以后進行調查。

這一次,我知道代碼中的某個地方出現了分段錯誤,我需要至少能夠記錄它,然后重新開始。

閱讀這里有一些解決方案,但每個解決方案都是一場激烈的戰爭,聲稱該解決方案實際上弊大於利,沒有真正的解釋。 我還找到了我考慮使用的這個答案,但我不確定它是否適合我的用例。

那么,從 C++ 上的分段錯誤中恢復的最佳方法是什么?

我建議你創建一個非常安全的小程序來監控有缺陷的程序。 如果錯誤程序以您不喜歡的方式退出,請重新啟動程序。

Posix 示例:

#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

#include <cstdio>
#include <iostream>

int main(int argc, char* argv[]) {
    if(argc < 2) {
        std::cerr << "USAGE: " << argv[0] << " program_to_monitor <arguments...>\n";
        return 1;
    }

    while(true) {
        pid_t child = fork();          // create a child process

        if(child == -1) {
            std::perror("fork");
            return 1;
        }

        if(child == 0) {
            execvp(argv[1], argv + 1); // start the buggy program
            perror(argv[1]);           // starting failed
            std::exit(0);              // exit with 0 to not trigger a retry
        }

        // Wait for the buggy program to terminate and check the status
        // to see if it should be restarted.

        if(int wstatus; waitpid(child, &wstatus, 0) != -1) {
            if(WIFEXITED(wstatus)) {
                if(WEXITSTATUS(wstatus) == 0) return 0; // normal exit, terminate

                std::cerr << argv[0] << ": " << argv[1] << " exited with "
                          << WEXITSTATUS(wstatus) << '\n';
            }
            if(WIFSIGNALED(wstatus)) {
                std::cerr << argv[0] << ": " << argv[1]
                          << " terminated by signal " << WTERMSIG(wstatus);
                if(WCOREDUMP(wstatus)) std::cout << " (core dumped)";
                std::cout << '\n';
            }
            std::cout << argv[0] << ": Restarting " << argv[1] << '\n';
        } else {
            std::perror("wait");
            break;
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM