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

About this user

Eino

« 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

   1  
   2  #include <stdio.h>
   3  #include <signal.h>
   4  
   5  void sig_handler(int signum)
   6  {
   7          printf("Catched signal %d", signum);
   8          exit(0);
   9  }
  10  
  11  int main()
  12  {
  13          int *ptr;
  14          struct sigaction new_action, old_action;
  15  
  16          // set up new handler to specify new action
  17          new_action.sa_handler = sig_handler;
  18          //sigemptyset (&new_action.sa_mask);
  19          new_action.sa_flags = 0;
  20          // attach SIGSEV to sig_handler
  21          sigaction(11, &new_action, NULL);
  22  
  23  
  24          printf("in loop\n");
  25          sleep(2);
  26  
  27          ptr = (int *)9;
  28          printf("%d\n", *ptr); // this should raise a SIGSEV
  29  }
  30  
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS