Skip to content

Instantly share code, notes, and snippets.

@khash
Created March 13, 2012 16:50
Show Gist options
  • Save khash/2029880 to your computer and use it in GitHub Desktop.
Save khash/2029880 to your computer and use it in GitHub Desktop.
eventmachine daemon start method
@pid_full = '/tmp/my_daemon.pid'
def run
EM.run{
Signal.trap('INT') { stop }
Signal.trap('TERM'){ stop }
# your daemon code runs here. This will not exit since it is running in EM
}
end
def get_pid
if File.exists?(@pid_full)
file = File.new(@pid_full, "r")
pid = file.read
file.close
pid
else
0
end
end
def start
pid = get_pid
if pid != 0
warn "Daemon is already running"
exit -1
end
pid = fork {
run
}
begin
file = File.new(@pid_full, "w")
file.write(pid)
file.close
Process.detach(pid)
rescue => exc
Process.kill('TERM', pid)
warn "Cannot start daemon: #{exc.message}"
end
end
def stop
pid = get_pid
begin
EM.stop
rescue
end
if pid != 0
Process.kill('HUP', pid.to_i)
File.delete(@pid_full)
puts "Stopped"
else
warn "Daemon is not running"
exit -1
end
end
@activeliang
Copy link

Awesome!!!Thanks!!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment