SIGSEGV Signal handling

Hello,
Can anybody tell me how can i handle segmentation fault signal, in C code?

First off, do not run code in production that gets a SIGSEGV signal. It is really bad practice.

The simplest way, and definitely not the best is to block the signal with a call to signal()

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

void my_signal_handler(int sig)
{
    write(STDERR_FILENO, "SEGFAULT!\n", 10); 
    signal(SIGSEGV, my_signal_handler); // reset the signal handler for SIGSEGV
    abort();
}

int main()
{
   signal(SIGSEGV, my_signal_handler); // initial set of signal handler
   /* do stuff here  */
   signal(SIGSEGV, SIG_DFL);  // restore default behavior

}

This is an example not meant to be used for production - it has potential race conditions, but you can use it to debug a SIGSEGV problem. In the my_signal_handler function be aware that you need to call only async safe functions like write() not std C lib funcions like printf()

Hello Jim,

Can you please explain this?

Is it because of the reason, that kernel might possibly deliver SIGSEGV when using printf, but I guess that's possible even with write() - I think am wrong.