Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I trigger a shell script and run in background (async) in Ruby?

Tags:

ruby

I have a shell script named test.sh. How can I trigger the test.sh from Ruby?

I want test.sh to run as a background process, what means in Ruby it is a ansync call.

STDERR and STDOUT also need to be written to a specific file.

Any ideas?

like image 899
TheOneTeam Avatar asked Aug 16 '12 06:08

TheOneTeam


1 Answers

@TanzeebKhalili's answer works, but you might consider Kernel.spawn(), which doesn't wait for the process to return:

pid = spawn("./test.sh")
Process.detach(pid)

Note that, according to the documentation, whether you use spawn() or manually fork() and system(), you should grab the PID and either Process.detach() or Process.wait() before exiting.

Regarding redirecting standard error and output, that's easy with spawn():

pid = spawn("./test.sh", :out => "test.out", :err => "test.err")
Process.detach(pid)
like image 73
Darshan Rivka Whittle Avatar answered Oct 23 '22 10:10

Darshan Rivka Whittle