Tuesday, September 17, 2013

Bash as occult text: starting a Unix daemon

So you've written your own Unix daemon, and now you need a start script to stick in /etc/init.d

As a socially responsible coder, you know your daemon needs to run under tightly policed user, like www or therebemonstershere.  So your init script will look something like this:

  su - therebemonstershere -c " { /usr/local/bin/mydaemon & } "

You'd also like to keep track of its pid, so you can kill your daemon later via /etc/init.d/mydaemon stop

  su - therebemonstershere -c " { /usr/local/bin/mydaemon & } ; echo \$! > /var/run/mydaemon.pid"

But this isn't enough: what about stdout and stderr?

  su - therebemonstershere -c " { /usr/local/bin/mydaemon > /var/log/mydaemon.log 2>&1 & } ; echo \$! > /var/run/mydaemon.pid"

Looking good!  But there's one more catch: when your terminal dies, your daemon will get a HUP signal and die too.   Probably in a week or so when you finally kill that xterm and forgot any of this happened.

  su - therebemonstershere -c " { nohup /usr/local/bin/mydaemon > /var/log/mydaemon.log 2>&1 & } ; echo \$! > /var/run/mydaemon.pid"