Question: I have a python script that'll be checking a queue and performing an action on each item:

```
# checkqueue.py
while True:
  check_queue()
  do_something()

```

How do I write a bash script that will check if it's running, and if not, start it. Roughly the following pseudo code (or maybe it should do something like `ps | grep`?):

```
# keepalivescript.sh
if processidfile exists:
  if processid is running:
     exit, all ok

run checkqueue.py
write processid to processidfile

```

I'll call that from a crontab:

```
# crontab
*/5 * * * * /path/to/keepalivescript.sh

```

Answer: 
The easiest way to do it is using flock on file. In Python script you'd do 

```
lf = open('/tmp/script.lock','w')
if(fcntl.flock(lf, fcntl.LOCK_EX|fcntl.LOCK_NB) != 0): 
   sys.exit('other instance already running')
lf.write('%d\n'%os.getpid())
lf.flush()

```

In shell you can actually test if it's running:

```
if [ `flock -xn /tmp/script.lock -c 'echo 1'` ]; then 
   echo 'it's not running'
   restart.
else
   echo -n 'it's already running with PID '
   cat /tmp/script.lock
fi

```

But of course you don't have to test, because if it's already running and you restart it, it'll exit with `'other instance already running'`

When process dies, all it's file descriptors are closed and all locks are automatically removed.
You should use monit, a standard unix tool that can monitor different things on the system and react accordingly.

From the docs: <http://mmonit.com/monit/documentation/monit.html#pid_testing>

```

check process checkqueue.py with pidfile /var/run/checkqueue.pid
       if changed pid then exec "checkqueue_restart.sh"

```

You can also configure monit to email you when it does do a restart.