Skip to content

Instantly share code, notes, and snippets.

@spraints
Created December 12, 2013 19:59
Show Gist options
  • Save spraints/7934407 to your computer and use it in GitHub Desktop.
Save spraints/7934407 to your computer and use it in GitHub Desktop.
#/ Usage: ruby timeout.rb <seconds> -- command arg arg arg
timeout, separator, *command = ARGV
timeout = timeout.to_f
if timeout <= 0.0 || separator != '--' || command.empty?
system "cat #$0 | grep ^#/ | cut -c4-"
exit 1
end
trap(:CHLD) { exit 0 }
pid = spawn(*command)
trap(:INT) { kill :INT, pid }
sleep timeout
$stderr.puts "Time's up!"
Process.kill :INT, pid
sleep 1.0
$stderr.puts "... TERM"
Process.kill :TERM, pid
sleep 1.0
$stderr.puts "... QUIT"
Process.kill :QUIT, pid
sleep 1.0
$stderr.puts "... KILL"
Process.kill :KILL, pid
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment