用代码最容易解释:
require 'timeout'
puts "this block will properly kill the sleep after a second"
IO.popen("sleep 60") do |io|
begin
Timeout.timeout(1) do
while (line=io.gets) do
output += line
end
end
rescue Timeout::Error => ex
Process.kill 9, io.pid
puts "timed out: this block worked correctly"
end
end
puts "but this one blocks for >1 minute"
begin
pid = 0
Timeout.timeout(1) do
IO.popen("sleep 60") do |io|
pid = io.pid
while (line=io.gets) do
output += line
end
end
end
rescue Timeout::Error => ex
puts "timed out: the exception gets thrown, but much too late"
end
我对这两个块的心智模型是相同的:
那么,我错过了什么?
编辑:drmaciver 在推特上建议,在第一种情况下,由于某种原因,管道套接字进入非阻塞模式,但在第二种情况下却没有。我想不出为什么会发生这种情况,也无法弄清楚如何获取描述符的标志,但这至少是一个合理的答案?致力于这种可能性。