Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait for process to finish using IO.popen?

Tags:

I'm using IO.popen in Ruby to run a series of command line commands in a loop. I then need to run another command outside of the loop. The command outside of the loop cannot run until all of the commands in the loop have terminated.

How do I make the program wait for this to happen? At the moment the final command is running too soon.

An example:

for foo in bar
    IO.popen(cmd_foo)
end
IO.popen(another_cmd)

So all cmd_foos need to return before another_cmd is run.

like image 911
Robin Barnes Avatar asked Aug 01 '09 19:08

Robin Barnes


1 Answers

Use the block form and read all the content:

IO.popen "cmd" do |io|
  # 1 array
  io.readlines

  # alternative, 1 big String
  io.read

  # or, if you have to do something with the output
  io.each do |line|
    puts line
  end

  # if you just want to ignore the output, I'd do
  io.each {||}
end

If you do not read the output, it may be that the process blocks because the pipe connecting the other process and your process is full and nobody reads from it.

like image 101
2 revs Avatar answered Sep 28 '22 07:09

2 revs