Skip to content

Instantly share code, notes, and snippets.

@wkf
Created March 12, 2014 13:25
Show Gist options
  • Save wkf/9506870 to your computer and use it in GitHub Desktop.
Save wkf/9506870 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'logger'
require 'timeout'
def trap_signal(s)
Signal.trap s do
Signal.trap('INT', 'IGNORE')
Signal.trap('TERM', 'IGNORE')
raise Interrupt
end
end
class Runit
def run
@pid = Process.spawn "/usr/bin/runsvdir -P /etc/service 'log:#{'.' * 395}'"
if $stdout.isatty
wait_to_die Process.spawn ('/bin/bash')
else
@status = wait_to_die
end
end
def stop
`/usr/bin/sv down /etc/service/*`
kill_self
kill_children
end
private
def kill(pid, signal = 'TERM')
Process.kill(signal, pid)
rescue Errno::ESRCH
end
def kill_self
kill(@pid)
Timeout::timeout(5) { wait_to_die }
rescue Timeout::Error
kill(@pid, 'KILL')
wait_to_die
end
def kill_children
kill(-1)
Timeout::timeout(5) { Process.waitpid(-1) and redo }
rescue Timeout::Error
kill(-1, 'KILL')
rescue Errno::ECHILD
end
def wait_to_die(pid = @pid)
while true do
break $?.exitstatus if Process.waitpid(-1) == pid
end
rescue Errno::ECHILD
'??'
end
end
trap_signal('INT')
trap_signal('TERM')
runit = Runit.new
log = Logger.new(STDOUT)
begin
log.info "Exited with status #{runit.run}"
rescue Interrupt
log.warn "Keyboard interrupt, halting"
ensure
runit.stop
end
@samccone
Copy link

nice

@samccone
Copy link

nicer

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