chillibear.com

Ruby daemons and at_exit

Silly mistake on my part, but took me a while before I saw the obvious.

If you’re writing a daemon in Ruby using the daemons gem (http://daemons.rubyforge.org) and want to have some code run when your script exits (is stopped by the daemon control), then your first thoughts would be to use the at_exit construct.

at_exit do
  # your code here
end

Fine, now in my case this code just wasn’t being run.

My code (with all the actual guff stripped out) was something like this:

require 'rubygems'
require 'daemons'
Daemons.run_proc() do
  loop {
    # code 
  }
end
at_exit do
  puts 'done'
end

Spot my silly mistake? If you move the at_exit code above the daemon loop then it works and is run on exit, in its current location it’s never even parsed. So the above should actully be:

require 'rubygems'
require 'daemons'
at_exit do
  puts 'done'
end
Daemons.run_proc() do
  loop {
    # code
  }
end

Written on 03 Oct 2009 and categorised in Ruby, tagged as atexit and daemons

Home, Post archive

site copyright Eric Freeman

Valid XHTML 1.0 Strict