Forum: Ruby daemonize, redirect stdin and stdout and write a pidfile

Posted by Guido De Rosa (gderosa)
on 2010-03-08 19:55
Hi!

the subject is a very standard requirement and should be done in a very
standard way: through ruby core, stdlib or some very popular gem, like
Daemons ( http://daemons.rubyforge.org/ )

Anyway, I don't know how to do something like this:

    # THIS CODE IS NOT VALID AND CERTAINLY WILL FAIL
    require 'daemons'
    require 'myclass'

    options = {
      :pidfile => '/var/run/myprog.pid'
      :stdout_to => '/var/log/myprog/myprog.log'
      :stderr_to => '/var/log/myprog/myprog.err'
    }

    Daemons.call(options) do
      MyClass.run! # contains an endless event loop
    end

Unfortunately, such options do not exist :-(

How to implement what is expressed in my pseudo-code?

BTW, I have rolled-my-own temporary solution, but I'm loking for
something more robust/standard:

    pid = fork do
      # redirects to logfiles
      STDOUT.reopen(config[:stdout_to], 'w')
      STDERR.reopen(config[:stderr_to], 'w')

      # buffered I/O on log files, sync them upon request!
      Signal.trap('USR1') do
        STDOUT.flush
        STDERR.flush
      end

      MyClass.run! # traps SIGINT/SIGTERM and should exit gacefully

      # the child process remove the pidfile on exit
      FileUtils.rm config[:pidfile] if File.exists? config[:pidfile]
    end

    # the parent process writes the pidfile
    if config[:pidfile]
      File.open config[:pidfile], 'w' do |f|
        f.write pid
      end
    end


Thanks for any suggestion!

Guido
Posted by Brian Candler (candlerb)
on 2010-03-09 11:07
Have you checked out the documentation of the PidFile class in the 
Daemons gem? It implements options :dir_mode=>:dir, 
:dir=>"/path/to/piddir"

Also, you can pass a filename as the first argument to daemonize(). 
However, both STDOUT and STDERR are written to the same file.

I found this out just through a little grepping.

    cd /var/lib/gems/1.8/gems/daemons-1.0.10/
    grep -iR pidfile .
    grep -iR stderr .
Please log in before posting. Registration is free and takes only a minute.
Existing account (Switch to SSL-encrypted connection)
NEW: Do you have a Google/GoogleMail or Yahoo account? No registration required!
Log in with Google account | Log in with Yahoo account
No account? Register here.