I am getting unexpected behaviour using popen3, which I want to use to run a command like tool ala cmd < file1 > file2. The below example hangs, so that stdout done is never reached. Using other tools than cat may cause hanging, so that stdin done is never reached. I suspect, I am suffering from buffering, but how do I fix this?
#!/usr/bin/env ruby
require 'open3'
Open3.popen3("cat") do |stdin, stdout, stderr, wait_thr|
stdin.puts "foobar"
puts "stdin done"
stdout.each_line { |line| puts line }
puts "stdout done"
puts wait_thr.value
end
puts "all done"
stdout.each_lineis waiting for further output fromcatbecausecat's output stream is still open. It's still open becausecatis still waiting for input from the user because its input stream hasn't been closed yet (you'll notice that when you opencatin a terminal and type infoobar, it will still be running and waiting for input until you press^dto close the stream).So to fix this, simply call
stdin.closebefore you print the output.