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.
Do you need the output of
popen
? If not, do you want to useKernel#system
or some other command?I think you'd need to assign the results from the
IO.popen
calls within the cycle to the variables, and keep callingread()
on them untileof()
becomes true on all.Then you know that all the programs have finished their execution and you can start
another_cmd
.Reading the output to a variable then calling
out.readlines
did it. I think thatout.readlines
must wait for the process to end before it returns.Credit to Andrew Y for pointing me in the right direction.
Apparently the canonical way to do this is:
Use the block form and read all the content:
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.
I suggest you use
Thread.join
to synchronize the lastpopen
call: