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

Dounx · April 15, 2020 · Last by Dounx replied at April 16, 2020 · 2726 hits
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
Reply to spike76

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

Dounx closed this topic. 16 Apr 14:23
You need to Sign in before reply, if you don't have an account, please Sign up first.