Question

This simple daemon (written using ruby daemons gem) prints numbers from 0 up to 9 until I stop the daemon using the stop command line option:

require 'rubygems'
require 'daemons'

options = {
  :multiple   => false,
  :ontop      => false,
  :backtrace  => true,
  :log_output => true,
  :monitor    => false
}

Daemons.run_proc('test.rb', options) do
  loop do
    10.times do |i|
      puts "#{i}\n"
      sleep(1)
    end
  end
end

I start the daemon with

ruby simple_daemon.rb start

and stop it with

ruby simple_daemon.rb stop

Is it possible to softly stop the daemon, letting it end its last loop before killing its process, so that I'm sure that it prints all the 10 numbers one last time?

Was it helpful?

Solution

You need to trap the TERM signal which is sent when you call stop and handle it yourself. Your code could be something like this :

Daemons.run_proc('test.rb', options) do
  stopped = false

  Signal.trap("TERM") do
    stopped = true
  end

  while not stopped
    10.times do |i|
      puts "#{i}\n"
      sleep(1)
    end
  end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top