Question

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:

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.

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.

Was it helpful?

Solution

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

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):

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 */
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top