Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux: handling a segmentation fault and getting a core dump

When my application crashes with a segmentation fault I'd like to get a core dump from the system. I do that by configuring before hand

ulimit -c unlimited

I would also like to have an indication in my application logs that a segmentation fault has occured. I do that by using sigaction(). If I do that however, the signal does not reach its default handling and a core dump is not saved.

How can I have both the system core dump an a log line from my own signal handler at the same time?

like image 945
shoosh Avatar asked May 22 '13 16:05

shoosh


People also ask

Is segmentation fault a core dump?

Core Dump/Segmentation fault is a specific kind of error caused by accessing memory that “does not belong to you.” When a piece of code tries to do read and write operation in a read only location in memory or freed block of memory, it is known as core dump.

How do you handle a segmentation fault?

The strategy for debugging all of these problems is the same: load the core file into GDB, do a backtrace, move into the scope of your code, and list the lines of code that caused the segmentation fault. This just loads the program called example using the core file called "core".


2 Answers

  1. Overwrite the default signal handler for SIGSEGV to call your custom logging function.
  2. After it is logged, restore and trigger the default handler that will create the core dump.

Here is a sample program using signal:

void sighandler(int signum)
{
  myLoggingFunction();

  // this is the trick: it will trigger the core dump
  signal(signum, SIG_DFL);
  kill(getpid(), signum);
}

int main()
{
   signal(SIGSEGV, sighandler);

   // ...
}

The same idea should also work with sigaction.

Source: How to handle SIGSEGV, but also generate a core dump

like image 134
Philipp Claßen Avatar answered Sep 22 '22 05:09

Philipp Claßen


The answer: set the sigaction with flag SA_RESETHAND and just return from the handler. The same instruction occurs again, causing a segmentation fault again and invoking the default handler.

like image 40
shoosh Avatar answered Sep 20 '22 05:09

shoosh