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

3 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

  2. Hi, I hope someone can give an answer to that:
    The last example works only because you WRITE, CLOSE and READ. But if you want to write, read, write, read etc. (how many times you want) the stdin/stdout read will stuck. This examples is for example not working and I have found NO solution to make it work:

    cmd = “mysql -uroot -p 2>&1″
    stdin = IO.popen(cmd,”a+” )
    stdin.puts “show databases;\n”
    puts “FIRST OUT:\n”

    puts stdin.gets
    stdin.puts “use mysql;\n”
    stdin.puts “show tables;\n”
    puts “SECOND OUT:\n”

    puts stdin.gets
    stdin.puts “select count(*) from user;\n”
    puts “THIRD OUT:\n”

    puts stdin.gets
    stdin.puts “exit\n”
    puts “LAST_OUT:\n”
    stdin.close
    puts stdin.gets

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s