# Daemonize, redirect stdin and stdout and write a pidfile

**URL:** <https://www.ruby-forum.com/t/daemonize-redirect-stdin-and-stdout-and-write-a-pidfile/184796>\
**Category:** Ruby\
**Created:** [March 8, 2010, 7:55pm UTC](https://www.ruby-forum.com/t/daemonize-redirect-stdin-and-stdout-and-write-a-pidfile/184796 "2010-03-08T19:55:48Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![gderosa](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/4da419/32.png) [@gderosa](https://www.ruby-forum.com/u/gderosa)\
**Post date:** [March 8, 2010, 7:55pm UTC](https://www.ruby-forum.com/t/daemonize-redirect-stdin-and-stdout-and-write-a-pidfile/184796/1 "2010-03-08T19:55:48Z")

</div>

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/](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

---

<div class="post-metadata">

**Author:** ![gderosa](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/4da419/32.png) [@gderosa](https://www.ruby-forum.com/u/gderosa)\
**Post date:** [March 9, 2010, 11:07am UTC](https://www.ruby-forum.com/t/daemonize-redirect-stdin-and-stdout-and-write-a-pidfile/184796/2 "2010-03-09T11:07:00Z")

</div>

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 .
```
