daemonize, redirect stdin and stdout and write a pidfile

G

Guido De Rosa

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
 
B

Brian Candler

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 .
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,073
Latest member
DarinCeden

Latest Threads

Top