下面的代码可以工作,但是如果 reader 和 writer 是跨父进程和子进程的共享资源,为什么他们首先要关闭?
reader, writer = IO.pipe
fork do
reader.close
writer.puts "foobar"
end
writer.close
puts reader.read
这对我来说没有任何意义,因为我认为应该像我编写的以下代码那样在写操作之后关闭读取器和写入器
reader, writer = IO.pipe
fork do
writer.puts "foobar"
writer.close
end
Process.wait
puts reader.read
reader.close
我不知道为什么它不起作用。谁能给我一个主意?
最佳答案
这是怎么回事,引自Stormier, Jesse . Working with UNIX Processes ( http://workingwithunixprocesses.com , 2012) p. 93:
...when the reader calls IO#read it will continue trying to read data until it sees an EOF (aka. end-of-file marker [2]). This tells the reader that no more data will be available for reading.
So long as the writer is still open the reader might see more data, so it waits. By closing the writer before reading it puts an EOF on the pipe so the reader stops reading after it gets the initial data. If you skip closing the writer then the reader will block and continue trying to read indefinitely.
如果您要大量使用 IO(包括套接字),我强烈建议您读一读他的书。
如您在其他问题中所述 How to maintain the TCP connection using Ruby?您可以使用 IO#flush
手动强制刷新缓冲区或通过设置 IO#sync=
将缓冲区设置为在写入/读取后始终同步为 true
。
关于ruby - 如果 IO.pipe 表现得像资源,为什么需要在子进程中关闭管道?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16383118/