我希望运行几个系统命令,并获得以下信息:
- 我希望在同一进程下的不同线程中运行每个命令
- 我希望捕获并存储输出和退出状态。
- 我希望在执行时间上设置超时以查找是否某些系统命令被卡住。
不幸的是,以下代码以:
/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
块(2 级)在 capture3'
偶尔,依赖于线程调度。例如,当将超时更改为 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
我曾尝试过rescue
inoutput_from
方法并关闭 o,但它也没有帮助。我觉得线程以某种方式在 popen3 实现中共享管道或一些变量。