How to run multiple external commands in the background in ruby

时间秒杀一切 提交于 2019-12-13 14:14:50

问题


Given this Unix shell script:

test.sh:

#!/bin/sh
sleep 2 &
sleep 5 &
sleep 1 &
wait

time ./test.sh

real 0m5.008s
user 0m0.040s
sys  0m0.000s

How would you accomplish the same thing in Ruby on a Unix machine?

The sleep commands are just an example, just assume that they are long running external commands instead.


回答1:


Straight from Process#waitall documentation:

fork { sleep 0.2; exit 2 }   #=> 27432
fork { sleep 0.1; exit 1 }   #=> 27433
fork {            exit 0 }   #=> 27434
p Process.waitall

Of course, instead of using Ruby's sleep, you can call whichever external command using Kernel#system, or backtick operator.




回答2:


#!/usr/bin/env ruby
pids = []
pids << Kernel.fork { `sleep 2` }
pids << Kernel.fork { `sleep 5` }
pids << Kernel.fork { `sleep 1` }
pids.each { |pid| Process.wait(pid) }



回答3:


To answer my own question (just found out about this):

​#!/usr/bin/ruby

spawn 'sleep 2'
spawn 'sleep 5'
spawn 'sleep 1'

Process.waitall

On ruby 1.8 you need to install the sfl gem and also require this:

require 'rubygems'
require 'sfl'


来源:https://stackoverflow.com/questions/4689592/how-to-run-multiple-external-commands-in-the-background-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!