DZone 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

Snippets has posted 5883 posts at DZone. View Full User Profile

Unix Custom Signal Handler

10.05.2006
| 10915 views |
  • submit to reddit
        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
}