Below is a function I am using to spawn subprocesses in a cross-platform manner on Ruby 1.9 with optional timeout support.
It works well most of the time. However I am experiencing a weird issue where process.spawn does not return (i.e. blocks) in some cases.
def execute!(args)
raise "invalid command specified" if args[:command].nil? or args[:command].empty?
command = args[:command]
timeout = args[:timeout] ? args[:timeout] : 60
readpipe, writepipe = IO.pipe
begin
pid = Process.spawn(command, :out => writepipe, :err => writepipe)
writepipe.close
rescue
readpipe.close
return "Execution of #{command} unsuccessful", 1
end
puts pid
process_output = ""
process_exitstatus = 1
begin
timeout_status = Timeout::timeout(timeout) {
_, process_status = Process.waitpid2(pid)
process_exitstatus = process_status.exitstatus
process_output = readpipe.readlines.join("")
process_output = "" if process_output.nil?
}
rescue Timeout::Error
process_output = "ERROR: #{command} took longer to execute than specified timeout! Killing process..."
process_exitstatus = 1
Process.kill('KILL', pid)
ensure
readpipe.close
end
return process_output, process_exitstatus
end
Can anyone spot any potential issues with this code that may be causing the problem I've described?