Detect if daemon is really running

You know the story, how your daemon die unexpectedly (mongrel,thin,BackgrounDRb) and on restart they complain about existing pid file (and assume its running). For BackgrounDRb we solved this irksome problem in following way:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def really_running? pid
  begin
    Process.kill(0,pid)
    true
  rescue Errno::ESRCH
    puts "pid file exists but process doesn't seem to be running restarting now"
    false
  end
end
 
def try_restart
  pid = nil
  pid = File.open(PID_FILE, "r") { |pid_handle| pid_handle.gets.strip.chomp.to_i }
  if really_running? pid
    puts "pid file already exists, exiting..."
    exit(-1)
  end
end

Simple, try sending signal “0” and if process responds to it, its alive otherwise pid file is stale and daemon can be safely restarted. There could be many more ways to solve this problem, for example to grep output of “ps aux”.

Leave a Reply

Your email address will not be published. Required fields are marked *