Ruby is a powerful dynamical programming language. You can easily use it to build large and complex software.

However, there are times when you just want to use it to make a basic script to automate your workflow, and simply run it by typing: ruby your_script.rb.

The problem comes when you want to let your script run forever, because if you close your console or terminal, the program will get closed too. To solve this problem, you need to make your script run in the background, and make it as a daemon. How?

Actually as of Ruby 1.9, this becomes a fairly simple process, you don’t need any extra library or gem, you can just add some code similar like below:

# daemonize
Process.daemon(true,true)

# write pid to a .pid file
pid_file = File.dirname(__FILE__) + "#{__FILE__}.pid"
File.open(pid_file, 'w') { |f| f.write Process.pid }

The first line of the code changes your script into a daemon process.

The class method #daemon accepts two arguments, the first argument controls current working directory. If you don’t set it to true, it will change the current working directory to the root (“/”). The second argument determines the outputs, unless the argument is true, daemon() will just ignore any standard input, standard output and standard error.

The second part of the code creates a .pid file with the same name as your script, and writes the process id into it. The benefit of this code is: you can use some process monitor tools like god, or monit to track the status of your script later on.

Finally, run your script again, and this time your script would just disappear from console. If you use command like:

ps -p your_pid

You will see that your script is running happily in the background.