Alex Rivera | Logout

Best practices for recovering from a segmentation fault

Asked 2011-12-06T14:40:34.847
16

I am working on a multithreaded process written in C++, and am considering modifying SIGSEGV handling using google-coredumper to keep the process alive when a segmentation fault occurs.

However, this use of google-coredumper seems ripe with opportunities to get stuck in an infinite loop of core dumps unless I somehow reinitialize the thread and the object that may have caused the core dump.

What best practices should I keep in mind when trying to keep a process alive through a core dump? What other 'gotchas' should I be aware of?

Thanks!

Edit
Report

2 Answers

49

It is actually possible in C. You can achieve it in quite a complicated way:

1) Override signal handler

2) Use setjump() and longjmp() to set the place to jump back, and to actually jump back to there.

Check out this code I wrote (idea taken from "Expert C Programming: Deep C Secrets" by Peter Van Der Linden):

#include <signal.h>
#include <stdio.h>
#include <setjmp.h>

//Declaring global jmp_buf variable to be used by both main and signal handler
jmp_buf buf;


void magic_handler(int s)
{

    switch(s)
    {

        case SIGSEGV:
        printf("\nSegmentation fault signal caught! Attempting recovery..");
        longjmp(buf, 1);
        break;
    }

    printf("\nAfter switch. Won't be reached");

}



int main(void) 
{

    int *p = NULL;

    signal(SIGSEGV, magic_handler);

    if(!setjmp(buf))
    {

         //Trying to dereference a null pointer will cause a segmentation fault, 
         //which is handled by our magic_handler now.
         *p=0xdead;

    }
    else
    {
        printf("\nSuccessfully recovered! Welcome back in main!!\n\n"); 
    }



    return 0;
}
answered 2012-10-10T16:31:43.550
1

From description of coredumper seems it's purpose not what you intending, but just allowing to make snapshots of process memory.

Personally, I wouldn't keep process after it triggered core dump -- it just so many ways it could be broken -- and would employ some persistence to allow data recovery after process is restarted.

And, yes, as parapura has suggested, better yet, find out what causing SIGSEGV and fix it.

answered 2011-12-06T14:45:50.267

Your Answer