Fork me on GitHub
Subscribe to RSS Feed

Kit Plummer
Software Engineer :: Techitect :: Evangelist
kitplummer@gmail.com
kitplummer (AIM,Yahoo!IM,Gtalk,Skype)

To the top »

Please share:

Sure, why not? How about Ruby scripts as daemons? Over the past couples years, where I’ve been working with Java I’ve had the need to daemonize a handful of different Java apps including ActiveMQ and ServiceMix and just recently Felix. Thanks to the Java Service Wrapper this is all pretty painless.

So, out of a “strange” need I found myself needing something similar to JSW for a Ruby script. Thanks to Google I found Daemons a Ruby script wrapper.

From the Daemons site:

Layout: suppose you have your self-written server myserver.rb:

  1. this is myserver.rb
  2. it does nothing really useful at the moment
loop do sleep(5) end

To use myserver.rb in a production environment, you need to be able to run myserver.rb in the background (this means detach it from the console, fork it in the background, release all directories and file descriptors).

Just create myserver_control.rb like this:

  1. this is myserver_control.rb
require ‘rubygems’ # if you use RubyGems require ‘daemons’ Daemons.run(‘myserver.rb’)

And use it like this from the console:

$ ruby myserver_control.rb start (myserver.rb is now running in the background) $ ruby myserver_control.rb restart (…) $ ruby myserver_control.rb stop

For testing purposes you can even run myserver.rb without forking in the background:

$ ruby myserver_control.rb run

An additional nice feature of Daemons is that you can pass additional arguments to the script that should be daemonized by seperating them by two hyphens:

$ ruby myserver_control.rb start — —file=anyfile —a_switch another_argument

And it is really that simple. Way cool.


Please comment:
blog comments powered by Disqus