我希望运行几个系统命令,并得到以下信息:
不幸的是下面的代码最终是:
/usr/lib/ruby/1.9.1/open3.rb:276:in
read': closed stream (IOError) from /usr/lib/ruby/1.9.1/open3.rb:276:incapture3' 中的块(2 级)
有时,取决于线程调度。例如,当将超时更改为 2 秒(或完全删除超时块)时,代码可以正常工作。
这是示例代码:
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
Run Code Online (Sandbox Code Playgroud)
我曾尝试rescueinoutput_from方法并关闭 o,但它也没有帮助。我感觉线程以某种方式共享 popen3 实现中的管道或一些变量。