Skip to content

Instantly share code, notes, and snippets.

@timuckun
Created October 4, 2010 01:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timuckun/609119 to your computer and use it in GitHub Desktop.
Save timuckun/609119 to your computer and use it in GitHub Desktop.
module Util
def Util.not_implemented
raise "not implemented yet"
end
def Util.kill_process_if_exists pid
running = true
begin
Process.kill(0, pid)
#if we get here the process is alive
rescue Errno::EPERM # changed uid
# puts "#{pid} has escaped my control!";
running = false
rescue Errno::ESRCH
#puts "#{pid} is deceased."; # or zombied
running = false
rescue
raise "Odd; I couldn't check the status of #{pid} : #{$!}"
end
if running
begin
Process.detach pid
rescue
puts "could not detach from process"
end
begin
Process.kill 'SIGKILL', pid
rescue => e
raise "count not kill process #{pid} #{e}"
end
end
end
def Util.shell_with_timeout(cmd, seconds = 3600)
#the default timeout is an hour. That's probably way too long
Timeout::timeout(seconds) {
@pid, @stdin, @stdout, @stderr = Open4.popen4(cmd)
ignored, @status = Process::waitpid2 @pid
if @status.exitstatus != 0
raise "Exit Status not zero"
end
}
@stdout ? @stdout.read.strip : ''
rescue Timeout::Error
raise "Process Timed out"
rescue => e
msg = @stderr ? @stderr.read.strip : ''
msg += e.to_s
raise "Error during execution of command #{cmd}\n #{msg}"
ensure
Util::kill_process_if_exists @pid
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment