-
-
Save anonymous/8a51721667d4b5a4cfae to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'timeout' | |
MAX_PROCESSES = 5 | |
MAX_TIME = 30 | |
command = #SOME LONG RUNNING PROCESS WITH LOTS OF OUTPUT | |
spoons = {} | |
finished_spoons = {} | |
unfinished_spoons = {} | |
MAX_PROCESSES.times do |i| | |
spoon = {} | |
spoon['read'], spoon['write'] = IO.pipe | |
spoon['fork'] = spawn(command, :out => spoon['write'], :err => spoon['write']) | |
spoons[spoon['fork']] = spoon | |
end | |
begin | |
Timeout.timeout(MAX_TIME) { | |
while !spoons.empty? do | |
pid, status = Process.wait2 | |
finished_spoons[pid] = spoons[pid] | |
spoons.delete(pid) | |
end | |
} | |
rescue Timeout::Error | |
puts "\nNot all processes ended before timeout. Killing remaining processes.\n" | |
kill_spoons = true | |
end | |
if kill_spoons | |
spoons.each do |key, spoon| | |
Process.kill(9, spoon['fork']) | |
unfinished_spoons[spoon['fork']] = spoon #make it un-finished | |
end | |
end | |
finished_spoons.each do |key, spoon| | |
spoon['write'].close | |
output = spoon['read'].read | |
spoon['read'].close | |
#do stuff with output | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment