Daemonizing Ruby Scripts

Daemons are processes that run in the background. Typically they are services like a web server. You can easily take any Ruby script and turn it in to a daemon that you can control with easy commands like start and stop. These code snippets demonstrate just how easy it is.

This is aimed at Linux users. First install the daemons gem. This was written to go along with the post on Writing a Mumble Bot in Ruby. That is an example of something we would want to daemonize.

gem install daemons

Server Code

This is a really lame server that doesn't do anything except print out the command line arguments it receives and then falls in to an infinite loop. Keep in mind that if you start the daemon it will fork to the background and you won't see the output. However, if you run the daemon it will not fork to a background process and you can see the output. This is useful just for seeing how the arguments are passed. See the section below about running and starting the daemon.

# server.rb

# Print out all command line arguments
ARGV.each do |arg|
    puts arg
end

# Loop forever...doing nothing
while true
end

Daemonizing

A second script will be used to control the server. We'll call this server_control.rb. It will simply wrap server.rb.

# server_control.rb

require 'daemons'

Daemons.run('server.rb')

Running the Daemon

# Fork to background
ruby server_control.rb start

# End the forked process that began with start
ruby server_control.rb stop

# Run without forking to background process
# Will require a CTRL-C or a kill to end
ruby server_control.rb run

# List running processes
# Look for server.rb
ps aux
# or
ps aux | grep server.rb

Passing Arguments

# Args start after double dashes
# Each arg is separated by a space
ruby server_control.rb start -- arg1 arg2 arg3=10

Learn More

There are few more things you can do with the daemons gem. You can start and stop daemons from within Ruby scripts which allows you to create a master control program for many services. For more information visit the Daemons page on RubyForge.

If you are wondering why you might want to use something like this, take a look at Writing a Mumble Bot in Ruby. That is an example of a program you want to run in the background. You could write a control script to manage the bot running in the background.