Spawn a background process in Ruby

寵の児 提交于 2019-11-26 09:35:24

问题


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


回答1:


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)

...



回答2:


better way to pseudo-deamonize:

`((/path/to/deamon1 &)&)` 

will drop the process into it's own shell.

best way to actually daemonize:

`service daemon1 start`

and make sure the server/user has permission to start the actual daemon. check out 'deamonize' tool for linux to set up your deamon.



来源:https://stackoverflow.com/questions/2504445/spawn-a-background-process-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!