title: Ruby daemon with clean shutdown
body: <p>I would like to make a ruby daemon that would gracefully shutdown with a kill command.
  I would like to add a signal trap that would wait until <code>#code that could take some time to run</code> finishes before shutting down.  How would I add that to something like this:</p>
  
  <pre><code>pid = fork do
     pid_file = "/tmp/pids/daemon6.pid"
     File.open(pid, 'w'){ |f| f.write(Process.pid) }
     loop do
        begin
           #code that could take some time to run
        rescue Exception =&gt; e
           Notifier.deliver_daemon_rescued_notification(e)
        end
        sleep(10)
     end
  end
  Process.detach pid
  </code></pre>
  
  <p>Also, would it be better to have that in a separate script, like a separate kill script instead of having it as part of the daemon code?  Like something <code>monit</code> or <code>God</code> would call to stop it?</p>
  
  <p>I appreciate any suggestions.</p>