29 December 2011

How to handle SIGSEGV, but also generate a core dump

Signals are the notification send to a process on the occurrence of an event.

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <signal.h>

void sighandler(int signum)
{
    printf("Process %d got signal %d\n", getpid(), signum);
    signal(signum, SIG_DFL);
    kill(getpid(), signum);
}

int main()
{
    signal(SIGSEGV, sighandler);
    printf("Process %d waits for someone to send it SIGSEGV\n",
        getpid());
    sleep(1000);

    return 0;
}
ulimit -c unlimited
echo "0" > /proc/sys/kernel/core_uses_pid
echo "core" > /proc/sys/kernel/core_pattern
$ ls
sigs.c
$ gcc sigs.c
$ ./a.out
Process 2149 waits for someone to send it SIGSEGV
Process 2149 got signal 11
Segmentation fault (core dumped)
$ ls
a.out*  core  sigs.c

Reference:
http://www.alexonlinux.com/signal-handling-in-linux
http://www.alexonlinux.com/how-to-handle-sigsegv-but-also-generate-core-dump
http://aplawrence.com/Linux/limit_core_files.html

No comments:

Post a Comment