adhearsion/adhearsion — pull request #266 by chewi (2013-03-01 17:07:38+00:00)
Title: [BUGFIX] Create PID file before daemonizing

The short gap between the parent process exiting and the PID file being written occasionally led to monitoring processes such as god believing that the server had failed to launch. Multiple instances would then be started with dire consequences.

You can reproduce the problem more reliably by inserting an artificial sleep in foundation/custom_daemonizer.rb.

```ruby
# This method causes the current running process to become a daemon
def daemonize(log_file = '/dev/null')
oldmode = 0
srand # Split rand streams between spawning and daemonized process
safefork and exit # Fork and exit from the parent

sleep 5 # !!!

# Detach from the controlling terminal
raise 'Cannot detach from controlled terminal' unless sess_id = ::Process.setsid
```

Then fire up ahn like so.

```
rm -f foo.pid && ahn daemon --pid-file foo.pid && cat foo.pid
```

You will see that foo.pid is not found. I found that even a sleep of 1 was enough to reproduce it reliably. After applying the fix, you can set the sleep to be as high as you like and foo.pid will always be found.

I tried to amend the tests but the heavy stubbing in Adhearsion::Initializer made this too tricky for me. Ideally we still want daemonize! to run and the block passed to daemonize to be called. It's the daemonize method itself that really needs stubbing. Could I have some help with this?