Archive for February 6th, 2007

keepalive.sh: restarting flaky applications

Tuesday, February 6th, 2007

Sometimes you just want an application to run in the background for whatever reason. One that tends to crash. Well, if you’re not there when it crashes, you can’t start it up again. So what to do? The obvious answer is “fix the damn application already!” But maybe you don’t have the source code. Or you don’t know how. Or you can’t be bothered. Or whatever. And you just want a way to automatically restart the application whenever it crashes.

I didn’t know how to do that before, so I never had a solution for those rare cases when this was needed. But it’s very easy to do.

#!/bin/sh
 
if [ "x$1" = "x" ]; then echo "usage: $0 <application>"; exit 1; fi
 
 
app=$1
echo "Running $app"
 
 
$app &
pid=$!
while ((1)); do
	if ! ps $pid; then
		echo "Restarting $app"
		$app &
		pid=$!
	fi
	echo "pid: $pid"
	wait $pid
	sleep 30
done

Download this code: keepalivesh

Here’s how keepalive.sh works.

  1. It starts the application.
  2. It captures the pid.
  3. Now it starts an infinite loop.
    1. Check the pid to see if the app is running.
    2. If the app is not running, start it and capture the pid.
    3. Otherwise just wait for it to finish.
    4. Goto 3.1.

It doesn’t matter if you stop the application in a standard way, if you kill it, or if it dies on its own. Within 30 seconds it will be restarted. The short delay is included so that an application that dies instantly won’t keep restarting and dieing all the time, bringing your system to its knees. Until you stop keepalive.sh, it will keep looping forever.