rubyfork

Capturing STDOUT from a forked process


I want to fork a process, wait for the child process to finish, then get the STDOUT from the child process. Here's code that doesn't work:

require 'stringio'

hold_stdout = $stdout
results = $stdout = StringIO.new

if pid = fork()
  Process.wait(pid)
else
  $stdout = hold_stdout
  puts 'stuff in child process'
  exit
end

$stdout = hold_stdout
puts 'results from child:'
puts results.string

That gives this output:

stuff in child process
results from child:

Not sure what to do here. If you ask me "why are you...?" the answer is because I don't know what I'm doing. Any help appreciated.


Solution

  • You can use pipes and redirect the stdout in the child process.

    reader, writer = IO.pipe
    
    if pid = fork()
      writer.close
      Process.wait(pid)
    else
      reader.close
      $stdout.reopen(writer)
      puts 'stuff in child process'
      exit
    end
    
    puts 'results from child:'
    puts reader.read
    

    This should print out what you want.