42

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

Nakilon
  • 34,866
  • 14
  • 107
  • 142
Dave DeLong
  • 242,470
  • 58
  • 448
  • 498

2 Answers2

69

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)

...
Marcel Jackwerth
  • 53,948
  • 9
  • 74
  • 88
  • If you're looking for something bigger (but still on the same host), consider daemon_controller. http://blog.phusion.nl/2008/08/25/daemon_controller-a-library-for-robust-daemon-management/ – Levi Mar 24 '10 at 02:30
  • 1
    Perfect! I knew about `fork` and `exec` (coming from a C background), but it was the `Process.detach()` that I was missing. Thanks! – Dave DeLong Mar 24 '10 at 03:18
  • This doesn't work as expected, for me, on OSX Lion and the pre-installed ruby. – nes1983 Dec 17 '11 at 11:19
  • 2
    And according to the docs, it shouldn't work. Detach doesn't mean that your child process won't be a child process any longer. What you want is to 'daemonize' it. – nes1983 Dec 17 '11 at 19:58
  • 3
    @nes1983 I never claimed that `detach` does that. I assume that you are talking about real daemons here - and then, yes, detach (and this question altogether) isn't what you are looking for. – Marcel Jackwerth Dec 17 '11 at 21:22
1

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.