Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

How do I execute a python script in the background if it is not already running? An example use for this is on the cron.

share|improve this question

2 Answers 2

if you want a script to start once at startup and theoretically it stays up then you should add it as a service to init.d with the appropriate runlevel set.

Of course if it should go down then you would want to to come back up.

to do that you can have a shell script run ps -aux | grep 'nameOfYourScript' like that. Of course don't include the grep command which will match as well lol. have that script check every five minutes with a cron like this */5 * * * * user checkScript.sh

the checkScript you make could be written to start up the program.

share|improve this answer
    
More generally: there is no foolproof method to check if a program is already running. Search this site with keywords such as daemontools. –  reinierpost Oct 12 '10 at 8:12

You could do something like this:

#!/bin/bash

# count the number of processes that match "NameOfProcess" but 
# exclude the grep process itself
pc=`ps -ef |grep "NameOfProcess" |grep -v grep |wc -l`

# if pc > 0, the process is already running and we can exit.
if [ $pc -gt 0 ] ; then
    echo "Application is already running, exiting."
    exit 0
fi

# othewise start the program
/path/to/program

Put this in crontab or start with

nohup /path/to/script.sh &

nohup will make sure that the process isnt shutdown if you exit the ssh session. An alternative to this is screen

share|improve this answer
    
I'd pick nohup over screen myself, but whatever works, works. –  pjmorse Oct 12 '10 at 12:50

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.