Search code examples
rubyprocessoutputforkspawn

How to get return value from a forked / spawned process in Ruby?


My simple test program:

pid = Process.spawn("sleep 10;date")

How can I place the output (eg stdout) of the "date" command in a variable when it is available? I don't want to use a file for the data exchange.


Solution

  • There are a whole bunch of ways to run commands from Ruby. The simplest for your case is to use backticks, which capture output:

    `sleep 10; date`
    # "Tue Jun 23 10:15:39 EDT 2015\n"
    

    If you want something more similar to Process.spawn, use the open3 stdlib:

    require 'open3'
    
    stdin, stdout, wait_thr = Open3.popen2("sleep 10; date")
    
    stdin.close
    Process.wait(wait_thr.pid)
    stdout.read
    # "Tue Jun 23 10:15:39 EDT 2015\n"
    stdout.close