views:

21

answers:

2

I am using the open4 gem and having problems reading from the spawned processes stdout. I have a ruby program, test1.rb:

print 'hi.' # 3 characters
$stdin.read(1) # block

And another ruby program in the same directory, test2.rb:

require 'open4'

pid, stdin, stdout, stderr = Open4.popen4 'ruby test1.rb'
p stdout.read(2) # 2 characters

When I run the second program:

$ ruby test2.rb

It just sits there forever without printing anything. Why does this happen, and what can I do to stop it?

A: 

I'm not an expert in process.

From my first sight of API document, the sequence of using open4 is like this: first send text to stdin, then close stdin and lastly read text from stdout.

So. You can the test2.rb like this

require 'open4'

pid, stdin, stdout, stderr = Open4.popen4 'ruby test1.rb'
stdin.puts "something" # This line is important
stdin.close # It might be optional, open4 might close itself.
p stdout.read(2) # 2 characters
OmniBus
A: 

I needed to change test1.rb to this. I don't know why.

print 'hi.' # 3 characters
$stdout.flush
$stdin.read(1) # block
Adrian