Daemonize, redirect stdin and stdout and write a pidfile

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 :frowning:

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

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 .

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs