新手问题 IO.pipe 是不是要等到 Write IO 完全关闭之后 Read IO 才能获取到数据?

Dounx · 2020年04月15日 · 最后由 Dounx 回复于 2020年04月16日 · 2725 次阅读
r, w = IO.pipe

if fork
  w.close
  until r.eof? do
    input = r.read(2048)
    puts input
  end
  r.close

  Process.wait
else
  r.close
  loop do
    str = gets.chomp
    break if str == 'exit'
    w << str
  end
  w.close
end

只有在输入 exit 之后,才可以打印输入的内容。

有没有方法可以使其只要输入就马上打印呢?(尝试过 IO#flush 好像没什么用)

tail -f xxx.log | grep xxx 这种管道又是怎么实现的?

问题在于读取的长度限制,r.read(2048) 只会在读取够了 2048 个字符时 (或者遇到了 eof) 才会返回,如果你改成 r.read(1),就会立即输出了。实际上一般的需求都是逐行输出,不用 read 而用 gets

r, w = IO.pipe

if fork
  w.close
  until r.eof? do
    input = r.gets
    puts input
  end
  r.close

  Process.wait
else
  r.close
  loop do
    str = gets
    break if str.chomp == 'exit'
    w << str
  end
  w.close
end
spike76 回复

确实是 read 的关系,我弄混了,感谢!

Dounx 关闭了讨论。 04月16日 14:23
需要 登录 后方可回复, 如果你还没有账号请 注册新账号