title: Trapping signals cleanly in Perl
body: <p>I have a simple Perl script that simply prints a line of text to stdout. What I want to accomplish is that while this script runs, if I (or someone else) issues a signal to that process to stop, I want it to trap that signal and exit cleanly. The code I have looks like the following</p>
  
  <pre><code>#!/usr/bin/perl -w
  
  $| = 1;
  use sigtrap 'handler' =&gt; \&amp;sigtrap, 'HUP', 'INT','ABRT','QUIT','TERM';
  while(1){
   print "Working...\n";
   sleep(2);
  }
  sub sigtrap(){
   print "Caught a signal\n";
   exit(1);
  }
  </code></pre>
  
  <p>While this works well when I actually hit ctrl-c from the command line, if I issue a</p>
  
  <pre><code>kill -9 &lt;pid&gt;
  </code></pre>
  
  <p>It just dies. How do I get it to execute something before exiting? My general idea is to use this framework to capture when this script dies on a server due to a server reboot for maintenance or failure.</p>
  
  <p>Thanks much in advance</p>