Read and Write to a Process using Ruby IO popen without blocking

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.

Advertisements

2 thoughts on “Read and Write to a Process using Ruby IO popen without blocking

  1. 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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s