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.
- It starts the application.
- It captures the pid.
- Now it starts an infinite loop.
- Check the pid to see if the app is running.
- If the app is not running, start it and capture the pid.
- Otherwise just wait for it to finish.
- 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.

Tuesday, February 6th, 2007