Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Unix Custom Signal Handler

This code allows one to catch a environment signal.
When the said signal is received (11 - SIGSEGV in this case), the signal handling function is called.

I used it to catch a SIGSEGV in a program, which occured regularly, but never when I used GDB.
In the sig_handler I put an infinite loop, and when the program was there I was able to attach
GDB to the program and backtrace to the function where the error occured

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

void sig_handler(int signum)
{
        printf("Catched signal %d", signum);
        exit(0);
}

int main()
{
        int *ptr;
        struct sigaction new_action, old_action;

        // set up new handler to specify new action
        new_action.sa_handler = sig_handler;
        //sigemptyset (&new_action.sa_mask);
        new_action.sa_flags = 0;
        // attach SIGSEV to sig_handler
        sigaction(11, &new_action, NULL);


        printf("in loop\n");
        sleep(2);

        ptr = (int *)9;
        printf("%d\n", *ptr); // this should raise a SIGSEV
}

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS