用C崩潰后監視並自動重啟另一個程序

[英]Monitor and automatically restart another program after crash with C


An application that I have running all the time (written in C++) randomly crashes since the last update but in between crashes it works well so I want to keep it running. It crashes with segfault. I tried writing a simple C program like this:

我一直在運行的應用程序(用C ++編寫)自上次更新后隨機崩潰,但在崩潰之間它運行良好,所以我想讓它繼續運行。它與segfault崩潰。我試着編寫一個這樣的簡單C程序:

while (1) {
    if (!program_is_running()) {
        fp = popen("/usr/bin/program", "r");
        fclose(fp);
    }
    else
        sleep(15);
}

My program seems to halt when the called program segfaults. Would exec or system (or something) calls be a better choice than popen? In my google adventures, I've read about (and thought about trying) daemontools supervise but I don't have any experience with that and it seems like it should be a relatively simple matter using C but then here I am asking the question so maybe not... At this point it is more curiosity than really trying to keep the program running as there are off the shelf tools to accomplish it.

當被調用的程序段錯誤時,我的程序似乎停止了。 exec或系統(或其他)調用會比popen更好嗎?在我的谷歌冒險中,我已經閱讀了(並考慮嘗試)daemontools監督,但我沒有任何經驗,似乎它應該是一個相對簡單的事情使用C但然后在這里我問這個問題所以也許不是......在這一點上,它比真正試圖保持程序運行更有好奇心,因為有現成的工具來完成它。

What is a simple and reliable way to restart a program that crashes with segmentation fault on a Ubuntu 12.04 machine using C? Assume program_is_running() returns 0 for false and PID for true.

使用C在Ubuntu 12.04計算機上重啟程序崩潰與程序崩潰的簡單可靠方法是什么?假設program_is_running()為false返回0,為true返回PID。

1 个解决方案

#1


5  

You can keep a program running using a simple shell script like the one in this answer.

您可以使用像本答案中的簡單shell腳本來運行程序。

If you insist on using C, you can use a combination of fork, exec* and waitpid to keep a process running indefinitely. Try something like (untested):

如果您堅持使用C,則可以使用fork,exec *和waitpid的組合來保持進程無限期運行。嘗試像(未經測試的):

while (1) {
    int status;
    pid_t pid = fork();
    if (-1 == pid) { perror("fork failed!"); exit(EXIT_FAILURE); }

    if (0  == pid) {
        /* Child */
        execlp("/usr/bin/program", NULL);
        perror("execlp failed!");
        exit(EXIT_FAILURE);
    }

    waitpid(pid, &status, 0);
    if (!WIFSIGNALED(status) || WTERMSIG(status) != SIGSEGV) {
        exit(EXIT_SUCCESS);
        /* The process didn't die because of a SIGSEGV, lets keep it dead */
    }
}

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2014/02/16/3f585a73fa6f620321f726b314f0f4fa.html



 
  © 2014-2022 ITdaan.com 联系我们: