How to start and stop a shell daemon from Ruby

How do I start a shell daemon and then stop it from the same Ruby script?

To be more specific, I would like my Ruby script:

  • start the server daemon using the shell command ( rails server | shotgun | etc.).
  • follow a couple of steps while the server is running.
  • make the server exit.

All preferred solutions supported by ruby ​​1.8 / 1.9 and unix / windows are preferred. (I read fork , for example, does not work on Windows).

+8
ruby
source share
4 answers

I highly recommend Ruby Daemons Stone . I think it has all the necessary functions.

Check section 3 of its README and pay special attention to the Daemons.call method, which allows you to demonize arbitrary code (in which you could just have a Kernel.system application).

+3
source share

Here's a similar problem with a working solution using the Windows command line:

https://serverfault.com/questions/35305/cmd-exe-how-to-starts-a-background-process-run-some-things-stops-background-pr

It's pretty dirty, but it's a trick.

Use Linux if you can, or just bash using the basic command line tools (installed using Git for Windows). Using bash, the solution is very simple:

 ./script/rails server --pid server.pid & ruby do_your_stuff.rb kill `cat server.pid` 

PS In any case, Windows is not recommended for the Rails environment. In the long run, you are likely to save a lot of time by switching to Linux, because you will not solve complex environmental problems such as this one.

0
source share

I couldn’t figure out how to do what I needed with the Ruby Daemons stone suggested by Peter, and ended up using systemu

 # command to start daemon command = "thin start" # here starting thin server as example status, stdout, stderr = systemu command do |cid| # do stuff here # ... Process.kill 9, cid # kill the daemon end 
0
source share

Take a look at the stone of Raad (Ruby as the Daemon) https://github.com/colinsurprenant/raad - it will work transparently using MRI Ruby and JRuby. (I am the author).

0
source share

All Articles