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.
Asked
Active
Viewed 1,288 times
2 Answers
1
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.

PHGamer
- 430
- 1
- 4
- 7
-
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 08:12
1
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

Avada Kedavra
- 1,294
- 2
- 13
- 19