title: How do I catch a KILL or HUP or User Abort signal?
body: <p>I have a script running on the background of my linux server and I would like to catch signals like reboot or anything that would kill this script and instead save any importante information before actually exiting.</p>
  
  <p>I think most of what I need to catch is, SIGINT, SIGTERM, SIGHUP, SIGKILL.</p>
  
  <p><strong>How do catch any of these signals and have it execute an exit function otherwise keep executing whatever it was doing ?</strong></p>
  
  <p>pseudo perl code:</p>
  
  <pre><code>#!/usr/bin/perl
  
  use stricts;
  use warnings;
  
  while (true)
  {
      #my happy code is running
      #my happy code will sleep for a few until its breath is back to keep running.
  }
  
  #ops I have detected an evil force trying to kill me
  #let's call the safe exit.
  sub safe_exit() 
  {
      # save stuff
      exit(1);
  }
  </code></pre>
  
  <p>pseudo php code:</p>
  
  <pre><code>&lt;?php
  
  while (1)
  {
      #my happy code is running
      #my happy code will sleep for a few until its breath is back to keep running.
  }
  
  #ops I have detected an evil force trying to kill me
  #let's call the safe exit.
  
  function safe_exit()
  {
      # save stuff
      exit(1);
  }
  ?&gt;
  </code></pre>