Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run multiple external commands in the background in ruby

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.

like image 350
Erik Avatar asked Oct 26 '25 02:10

Erik


2 Answers

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.

like image 181
Mladen Jablanović Avatar answered Oct 28 '25 16:10

Mladen Jablanović


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'
like image 29
Erik Avatar answered Oct 28 '25 18:10

Erik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!