Created
March 13, 2012 16:50
-
-
Save khash/2029880 to your computer and use it in GitHub Desktop.
eventmachine daemon start method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Awesome!!!Thanks!!!