質問

I am learning ruby popen, and I am interested in a simple program:

pipe = IO.popen("-","w+")
if pipe
  pipe.puts "Get a job!"
  STDERR.puts "Child says: #{pipe.gets.chomp}"
else
  STDERR.puts "Dad says: #{gets.chomp}"
  puts "OK"
end

Then the produces look like that:

Dad says: Get a job!
Child says: OK

But, when I update the code by removing STDOUT:

pipe = IO.popen("-","w+")
if pipe
  pipe.puts "Get a job!"
  puts "Child says: #{pipe.gets.chomp}"
else
  puts "Dad says: #{gets.chomp}"
  puts "OK"
end

Then result changes to this:

Child says: Dad says: Get a job!

It misses "OK"! So, why?

役に立ちましたか?

解決

Without STDERR., puts write the output to the stdout. stdout in the child process is pipe. Anything written to the stdout is not printed, but sent to the pipe.

The child process write 2 lines.

  1. Dad say: Get a job!
  2. OK

The parent process read a line (Dad say: Get a job!), and print that.

Child says: Dad say: Get a job!
            ^^^^^^^^^^^^^^^^^^^ -- read from the pipe (stdout of child process).

If you also want print OK, call pipe.gets twice or use pipe.read to read all output of children:

pipe = IO.popen("-","w+")
if pipe
  pipe.puts "Get a job!"
  puts "Child says: #{pipe.read}"
else
  puts "Dad says: #{gets.chomp}"
  puts "OK"
end
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top