How to run multiple external commands in the background in ruby

Given this shell Unix 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 do the same in Ruby on a Unix machine?

Hibernate commands are just an example, just suppose they use external commands more.

+3
source share
3 answers

Directly from the Process#waitalldocumentation:

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, sleepyou can call any external command using Kernel#system, or the backtick operator .

+5
source
#!/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) }
+1
source

( ):

#!/usr/bin/ruby

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

Process.waitall

1.8 sfl, :

require 'rubygems'
require 'sfl'
0

Source: https://habr.com/ru/post/1785387/


All Articles