<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DZone Snippets: signals code</title>
    <link>http://snippets.dzone.com/posts</link>
    <pubDate>Sat, 04 Oct 2008 09:11:15 GMT</pubDate>
    <description>DZone Snippets: signals code</description>
    <item>
      <title>Unix Custom Signal Handler</title>
      <link>http://snippets.dzone.com/posts/show/2784</link>
      <description>This code allows one to catch a environment signal.&lt;br /&gt;When the said signal is received (11 - SIGSEGV in this case), the signal handling function is called.&lt;br /&gt;&lt;br /&gt;I used it to catch a SIGSEGV in a program, which occured regularly, but never when I used GDB.&lt;br /&gt;In the sig_handler I put an infinite loop, and when the program was there I was able to attach&lt;br /&gt;GDB to the program and backtrace to the function where the error occured&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;#include &lt;stdio.h&gt;&lt;br /&gt;#include &lt;signal.h&gt;&lt;br /&gt;&lt;br /&gt;void sig_handler(int signum)&lt;br /&gt;{&lt;br /&gt;        printf("Catched signal %d", signum);&lt;br /&gt;        exit(0);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;int main()&lt;br /&gt;{&lt;br /&gt;        int *ptr;&lt;br /&gt;        struct sigaction new_action, old_action;&lt;br /&gt;&lt;br /&gt;        // set up new handler to specify new action&lt;br /&gt;        new_action.sa_handler = sig_handler;&lt;br /&gt;        //sigemptyset (&amp;new_action.sa_mask);&lt;br /&gt;        new_action.sa_flags = 0;&lt;br /&gt;        // attach SIGSEV to sig_handler&lt;br /&gt;        sigaction(11, &amp;new_action, NULL);&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;        printf("in loop\n");&lt;br /&gt;        sleep(2);&lt;br /&gt;&lt;br /&gt;        ptr = (int *)9;&lt;br /&gt;        printf("%d\n", *ptr); // this should raise a SIGSEV&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Thu, 05 Oct 2006 16:13:38 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/2784</guid>
      <author>eino (Eino)</author>
    </item>
  </channel>
</rss>
