无法读取正在写入的命名管道

时间:2021-05-27 22:55:40

标签: ruby named-pipes

我有一个数据流要写入命名管道:

named_pipe = '/tmp/pipe' # Location of named pipe
File.mkfifo(named_pipe) # Create named pipe
File.open(named_pipe, 'w+') # Necessary to not get a broken pipe when ⌃C from another process later on

system('youtube-dl', '--newline', 'https://www.youtube.com/watch?v=aqz-KE-bpKQ', out: named_pipe) # Output download progress, one line at a time

问题是,虽然我可以 cat /tmp/pipe 并获取信息,但我无法从另一个 Ruby 进程读取文件。我尝试过 File.readlinesFile.read 寻找、File.open 然后阅读,以及其他我不再记得的东西。其中一些挂起,另一些出错。

在纯 Ruby 中如何获得与 cat 相同的结果?

注意我不必使用 system 发送到管道(Open3 是可以接受的),但任何需要外部依赖的解决方案都是不行的。

1 个答案:

答案 0 :(得分:2)

看起来 File.readlines/IO.readlinesFile.read/IO.read 需要先加载整个临时文件,这样您就看不到任何打印出来了。

尝试File#each/IO.foreach,它逐行处理一个文件,它不需要将整个文件加载到内存中

File.foreach("/tmp/pipe") { |line| p line }
# or
File.open('/tmp/pipe','r').each { |line| p line }