Ruby daemon with clean shutdown

I would like to make a ruby ​​daemon that gracefully completes the kill command. I would like to add a signal trap that will wait for #code that could take some time to run to #code that could take some time to run before closing. How to add this to the following:

 pid = fork do pid_file = "/tmp/pids/daemon6.pid" File.open(pid, 'w'){ |f| f.write(Process.pid) } loop do begin #code that could take some time to run rescue Exception => e Notifier.deliver_daemon_rescued_notification(e) end sleep(10) end end Process.detach pid 

It would also be better to have this in a separate script, as a separate kill script instead of having it as part of the daemon code? How is something monit or God invoked to stop it?

I appreciate any suggestions.

+7
source share
1 answer

You can catch Interrupt , for example:

 pid = fork do begin loop do # do your thing sleep(10) end rescue Interrupt => e # clean up end end Process.detach(pid) 

You can do the same with Signal.trap('INT') { ... } , but with sleep I think it's easier to catch the exception.

Update: This is a more traditional way of doing this, and it ensures that the loop always ends the full transition before it stops:

 pid = fork do stop = false Signal.trap('INT') { stop = true } until stop # do your thing sleep(10) end end 

The downside is that it will always do sleep , so there will almost always be a delay until the process stops after you kill it. You can probably get around this, sleep in packages, or do a combination of options (saving Interrupt just around sleep or something else).

+7
source

All Articles