在Ruby中生成后台进程 [英] Spawn a background process in Ruby

查看:155
本文介绍了在Ruby中生成后台进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为一个学校项目编写一个ruby引导脚本,该引导过程的一部分是启动几个后台进程(这些进程均已编写且可以正常运行).我想做的事情大致如下:

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 &`

但是,这在执行daemon1的第一次调用时阻塞.我已经看到了对Process.spawn方法的引用,但这似乎是1.9+的功能,而且我仅限于Ruby 1.8.

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)?

推荐答案

只要您在POSIX操作系统上工作,就可以使用forkexec.

As long as you are working on a POSIX OS you can use fork and exec.

fork =创建一个子进程

exec =用另一个进程替换当前进程

exec = Replace current process with another process

然后您需要通过Process.detach通知您的主流程对创建的子流程不感兴趣.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆