Skip to content

Instantly share code, notes, and snippets.

@chetan
Created June 6, 2013 00:48
Show Gist options
  • Save chetan/5718542 to your computer and use it in GitHub Desktop.
Save chetan/5718542 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require "daemons"
require "fileutils"
module Daemons
class Controller
def catch_exceptions(&block)
begin
block.call
@error = false
rescue CmdException, OptionParser::ParseError => e
@error = true
puts "ERROR: #{e.to_s}"
puts
print_usage()
rescue RuntimeException => e
@error = true
puts "ERROR: #{e.to_s}"
end
end
def error?
@error == true
end
end
end
class DaemonStarter
def initialize(name)
@filename = File.expand_path(name + ".starting")
@pid = File.expand_path(name = ".pid")
end
# Check if the daemon should start
def start?
if not(ARGV.include? "start" or ARGV.include? "restart") then
# some command other than start or restart
return true
end
return false if File.exists? @filename
FileUtils.touch(@filename)
@file = File.new(@filename)
if @file.flock(File::LOCK_EX|File::LOCK_NB) == false then
return false
end
return true
end
def cleanup!
puts "cleanup: #{File.exists? @pid}"
begin
@file.flock(File::LOCK_UN) # unlock
rescue => ex
end
begin
File.delete(@filename) if File.exists? @filename
rescue => ex
end
end
end
starter = DaemonStarter.new(File.expand_path("race"))
exit if not starter.start?
Daemons.run_proc('race', :log_output => true, :dir => Dir.pwd, :dir_mode => :normal) do
starter.cleanup!
loop do
puts "hello from process #{Process.pid}"
sleep 5
end
end
starter.cleanup! if Daemons.controller.error?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment