ruby - 如果 IO.pipe 表现得像资源,为什么需要在子进程中关闭管道?

标签 ruby ipc

下面的代码可以工作,但是如果 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/

相关文章:

ruby - ruby 中迭代器的索引计数方法?

ruby-on-rails - Ruby:打开 URI。从远程 url 获取文件名

struct - 将结构从一个进程发送到另一个进程的最简单方法是什么?

c++ - 使用 ShellExecute 的进程之间的 IPC

html - 使用 jbuilder 返回未转义的 html

ruby-on-rails - Rails 中的过滤表单?

ruby - 如何像在 Prime 类中一样在 Ruby 中创建默认实例?

shell - 如何从 shell 脚本调用 GAP 函数?

c - C 中的进程间通信

c# - 什么是IPC?我该如何使用它?