Daemonizing Ruby Applications with Process


Sometimes we need our Ruby application runs in background. The best way to achieve so is to make it a background process using gems like daemons. They are easy to install and use. However, this post aims to do the same without any third-party library.

Ruby has a built-in library called Process. It manages the current process that runs the Ruby application. What we're going to do is to output the pid and let it do its own work. Here's a basic Ruby application name hello.rb:

loop do
  puts "hello world"
  sleep 1
end

Running it will keep looping the message "hello world". Nevertheless, if we close the terminal session, this application will stop too. If we want to daemonize it, this is where Process library comes in. We can simply add a .daemon method and it will detach from the session.

So it goes like this:

Process.daemon

loop do
  puts "hello world"
  sleep 1
end

And we start the program as usual:

$ ruby hello.rb

Note that we daemonize it at the first place, so that the rest of the program will run in background. We can use terminal commands like:

$ ps aux | grep hello.rb

We will see an output like this:

user      26742   0.0  0.0  2456812    876   ??  S    12:38AM   0:00.00 ruby hello.rb

The first number is the pid, which serves to identify the process when we want to stop it. The following command will do so when we want to stop the program.

$ kill -9 26742