Skip to content

Instantly share code, notes, and snippets.

@activeliang
Forked from khash/em.rb
Created May 14, 2020
Embed
What would you like to do?
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment