Read and Write to a Process using Ruby IO popen without blocking
Posted: February 19, 2010 Filed under: Ruby, Unix | Tags: blocking, command, IO, popen, Ruby, stdin, stdout 2 Comments »Once in a while you need to control an interactive command line tool. I kept getting a block when trying to read from a ruby IO popen pipe that was waiting for input. Here is my simple solution/workaround:
sh_process = IO.popen('sh > out.log', 'w')
f = File.open("out.log", "r")
sh_process.puts("ls")
f.read
sh_process.puts("uptime")
f.read
...
f.close
Basically, just create a temp file and read from that. A little hackish, but it works.
Hi,
I’ve found this solution when googling around this problem, and I just want to suggest another (and probably better) solution for this problem.
The problem with this solution might occur with concurrent access.
The better solution might be:
ret = IO.popen(‘sh’, ‘r+’) do |f|
f.puts(“ls”)
f.close_write
f.read
end
Why it requires the ‘w’ is beyond me…