在 Ruby 中生成后台进程 [英] Spawn a background process in Ruby
问题描述
我正在为一个学校项目编写一个 ruby 引导脚本,这个引导过程的一部分是启动几个后台进程(它们被编写并正常运行).我想做的是类似的事情:
`/path/to/daemon1 &``/path/to/daemon2 &``/path/to/daemon3 &`
然而,这会在第一次调用执行 daemon1 时阻塞.我见过对 Process.spawn
方法的引用,但这似乎是 1.9+ 的特性,而且我仅限于 Ruby 1.8.
我也尝试从不同的线程执行这些守护进程,但我希望我的引导脚本能够退出.
那么我该如何启动这些后台进程,以便我的引导脚本不会被阻塞并且可以退出(但仍然让守护进程在后台运行)?
只要你在 POSIX 操作系统上工作,你就可以使用 fork
和 exec
.>
fork
= 创建子进程
exec
= 用另一个进程替换当前进程
然后您需要通过 Process.detach
通知您的主进程对创建的子进程不感兴趣.
job1 = fork do执行/path/to/daemon01"结尾Process.detach(job1)...
I'm writing a ruby bootstrapping script for a school project, and part of this bootstrapping process is to start a couple of background processes (which are written and function properly). What I'd like to do is something along the lines of:
`/path/to/daemon1 &`
`/path/to/daemon2 &`
`/path/to/daemon3 &`
However, that blocks on the first call to execute daemon1. I've seen references to a Process.spawn
method, but that seems to be a 1.9+ feature, and I'm limited to Ruby 1.8.
I've also tried to execute these daemons from different threads, but I'd like my bootstrap script to be able to exit.
So how can I start these background processes so that my bootstrap script doesn't block and can exit (but still have the daemons running in the background)?
As long as you are working on a POSIX OS you can use fork
and exec
.
fork
= Create a subprocess
exec
= Replace current process with another process
You then need to inform that your main-process is not interested in the created subprocesses via Process.detach
.
job1 = fork do
exec "/path/to/daemon01"
end
Process.detach(job1)
...
这篇关于在 Ruby 中生成后台进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!