Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Unix Custom Signal Handler

DZone's Guide to

Unix Custom Signal Handler

·
Free Resource
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 
  
   
#include 
   
    

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 (≠w_action.sa_mask);
        new_action.sa_flags = 0;
        // attach SIGSEV to sig_handler
        sigaction(11, ≠w_action, NULL);


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

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


   
  
Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}