如何在 Ruby 中触发 shell 脚本并在后台(异步)运行? [英] How can I trigger a shell script and run in background (async) in Ruby?
问题描述
我有一个名为 test.sh 的 shell 脚本.如何从 Ruby 触发 test.sh?
I have a shell script named test.sh. How can I trigger the test.sh from Ruby?
我希望 test.sh 作为后台进程运行,这在 Ruby 中意味着它是一个异步调用.
I want test.sh to run as a background process, what means in Ruby it is a ansync call.
STDERR 和 STDOUT 也需要写入特定文件.
STDERR and STDOUT also need to be written to a specific file.
有什么想法吗?
推荐答案
@TanzeebKhalili 的回答有效,但您可能会考虑 Kernel.spawn(),它不等待进程返回:
@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)
注意,根据文档,无论是使用spawn()
还是手动fork()
和system()
,都应该在退出之前获取 PID 和 Process.detach()
或 Process.wait()
.
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.
关于重定向标准错误和输出,使用 spawn()
很容易:
Regarding redirecting standard error and output, that's easy with spawn()
:
pid = spawn("./test.sh", :out => "test.out", :err => "test.err")
Process.detach(pid)
这篇关于如何在 Ruby 中触发 shell 脚本并在后台(异步)运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!