I wish to run several system commands, and get the following:
- I wish to run each of the commands in different thread under the same process
- I wish to capture and store the output and exit status.
- I wish to set timeout on the execution time to find if some system command is stuck.
Unfortunately the following code ends up with:
/usr/lib/ruby/1.9.1/open3.rb:276:in
read': closed stream (IOError) from /usr/lib/ruby/1.9.1/open3.rb:276:in
block (2 levels) in capture3'
occasionally, dependant on threads scheduling. When changing timeout to 2 seconds, for example (or removing the timeout block at all), the code works.
Here is a sample code:
require 'open3'
require 'timeout'
def output_from(command)
o, e, s = Open3.capture3(command)
return o
end
attempts = 0
Thread.abort_on_exception = true
for i in 0..5
Thread.new {
begin
Timeout::timeout(0.0001) {
output = output_from('cat /proc/cpuinfo')
}
rescue Timeout::Error => e
attempts+=1
retry unless attempts > 2
end
}
end
puts attempts
I had tried to rescue
in output_from
method and close o, but it did not help as well.
I get the feeling that somehow the threads shares the pipes or some variables in popen3 implementation.