raw code

Write a PID file in bash

Robert Eisele

To write a PID-file of a just created background process you can simply use the variable $! like this:

/usr/local/bin/program &
echo $! > /var/run/program.pid

I need this to fork a little daemon written in PHP. Yes, I could use pcntl_fork(), but my goal was, saving the recompilation of PHP and any changes to the code. Normally, I used a little tricky syntax to fork the PHP-process:

((/usr/local/php -f /var/daemon/queue.php)&)

This is quite cool, because the process now runs in the background, and we can close the shell. But what happens, when the process dies? This is a problem and I tried to combine the first and the second snippet to get the PID in a file and look continually over the process. First I wrote the backgrounding to a little shellscript:

#!/bin/bash

/usr/local/php -f /var/daemon/queue.php &
echo $! > /var/run/queue.pid

And started the whole thing by ((queue.sh) &).

But let's try to combine both in a single statement. The result of my testing was an easy to read command, which spawns a programm as a daemon and additionaly writes it's PID to a file:

((/usr/local/php/bin/php -f /root/queue.php) & echo $! > /var/run/queue.pid &)

For now, we have the process running and the according PID in a file. Let's write a little watchdog, that will watch over the health of our daemon and creates a new process, when our daemon dies for some reason. I think the best solution for this job is a cron job. So let's pack the stuff in a little shellscript.

#!/bin/bash
pid=`cat /var/run/queue.pid`

if [ ! -e /proc/$pid -a /proc/$pid/exe ]; then
	mail -s "Queue failed" failed@example.com <<EOF
Queue on host $(hostname) failed and restarted
EOF
fi