I currently have a Python webserver application running and I would like to use a python script for cron job to check if the application is running, else start the application.
I have the following code as below:
import os
string = os.popen('ps aux')
n = 0
for line in string.readlines():
if "python webserver.py" in line:
n+=1
if n < 1:
os.system('python webserver.py')
Now the script has executed the application. But what I want is for the script to start the application and exit, leaving the application running. Is there any ways to do so? Thanks in advance.
I like to do this with a shell script similar to the following. It is simple and has low likelihood of errors. Generally I put this in a while loop with sleep at the end, but cron works fine too.
As you can see it requires your process to write its PID into a file when it starts up. This avoids problems with grepping ps output because it can be tricky to get a regular expression that always works no matter what new process names come onto your server in future. The PID file is dead certain.
kill -0is a little known way of checking if a process is running and is simpler than checking for a directory in/proc. The line withpid=1is there because the checker is not root therefore the kill check will always fail if you can’t send signals to the process. That is there to cover the first time that myproc is run on this server. Note that this means that the checking script must not run asroot(generally good practice) but must run as the same user which runs the process you are checking.If you really want to do this in Python, then the
osmodule has access to PIDs and has akillmethod. However it doesn’t return a shell exitcode, insteados.killthrowsOSErrorexceptions which you can handle in atry–catchblock. The same principle applies of using signal 0 to detect whether the process exists or not but there is a slim chance that your process has died and another process now has the same pid, so do handle that case in yourtry–catch.