title: Signal handling in pthreads
body: <p>I have created a pthread, and installed a signal handler inside that, same way as we do in <code>main( )</code> function. The thread's signal handler is a separate function. Surprisingly, it is not working, that is the thread's signal handler is not able to catch signals.</p>
  <p>Here is the code:</p>
  <pre><code>#include &lt;pthread.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;signal.h&gt;
  #include &lt;string.h&gt;
  
  typedef struct data
  {
   char name[10];
   int age;
  }data;
  
  void sig_func(int sig)
  {
   printf(&quot;Caught signal: %d\n&quot;,sig);
   signal(SIGSEGV,sig_func);
  }
  
  void func(data *p)
  {
   printf(&quot;This is from thread function\n&quot;);
   signal(SIGSEGV,sig_func); // Register signal handler inside thread
   strcpy(p-&gt;name,&quot;Mr. Linux&quot;);
   p-&gt;age=30;
   sleep(2); // Sleep to catch the signal
  }
  
  int main()
  {
   pthread_t tid;
   pthread_attr_t attr;
   data *ptr;
  
   pthread_attr_init(&amp;attr);
   pthread_create(&amp;tid,&amp;attr,(void*)func,ptr);
   pthread_kill(tid,SIGSEGV);
  
   pthread_join(tid,NULL);
   printf(&quot;Name:%s\n&quot;,ptr-&gt;name);
   printf(&quot;Age:%d\n&quot;,ptr-&gt;age);
  }
  </code></pre>
  <p>Output:</p>
  <blockquote>
  <p>Segmentation fault (which means the signal is not caught by handler)</p>
  </blockquote>