keepalive.sh: restarting flaky applications

February 5th, 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

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.

:: random entries in this category ::

4 Responses to "keepalive.sh: restarting flaky applications"

  1. erik says:

    One step closer to inventing time loops

  2. sinx says:

    Nice, Unix command "watch" do something very simillar... i think but i'm not sure (used it only twice). But your script looks quite nice ;) ...

    if ! ps $pid; then

    strange that the brackets [] are not needed in this part of code ... it's sh not bash maybe this is reason ;)

  3. numerodix says:

    No, watch has nothing to do with that. It just runs a command at a set interval, it doesn't check that it keeps running or anything. However there was another way of doing this that I read on newsforge.com but can't remember. :/

    I think the brackets threw an error actually. If you just invoke commands rather than comparing values then don't use brackets, that's my impression. Otherwise

    if [ ! `ps $pid` = "something" ]; then

  4. Dieter@be says:

    fwiw, the if statement in both bash and sh just check the exit code of a command.
    '[' is an alias for test in bash, so if you do if [ args ], it will just execute test with the given arguments and evaluate it's exitcode.