Over a million developers have joined DZone.

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


void sig_handler(int signum)
        printf("Catched signal %d", signum);

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");

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


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}