Check if a process is already running on a server

Viewed 157

I own a server that I want to run a Python (2.7) threaded server script on it.

I have a cron job that validates every minute that the script is up and running, if it is, let it continue do it's work, else launch it.

I have searched and found several solutions to make this check work, but none of the solutions I found seem to work.

The Python script that I want to ALWAYS run on the server is called "serverListener.py"

So what happens, the cron job runs the script wd.sh which contains:

#!/bin/bash
python /home2/ofekafsc/public_html/cgi-bin/wd.py

Now, the script wd.py has a solution in which I tried to use, but I never receive true.

I am trying to check whether the process is running, if so do nothing, else launch it. The problem I have is it ALWAYS returns FALSE (as for the server is NOT running)

Code:

#!/usr/bin/python
import subprocess
import psutil

def running3(program, scriptname):
    for pid in psutil.pids(): # Iterates over all process-ID's found by psutil,
        try:
            p = psutil.Process(pid) 
            if program in p.name(): 
                for arg in p.cmdline():
                    if scriptname in str(arg):  
                        return True
                    else:
                        pass
            else:
                pass
            except Exception as e:
                try:
                    f = open("/home2/ofekafsc/public_html/cgi-bin/ERRORLOG.txt", "w+")
                    f.write(str(e))
                    f.close()
                except Exception as e:
                    print(str(e))
if(running3("python", "serverListener.py")):
    print("RUNNING")
    sys.exit()
else:
    subprocess.call("/home2/ofekafsc/public_html/cgi-bin/serverListener.py")

As mentioned, the above code did not do the job.

This is what the loop finds:

Program name : python
arg in cmdline: python
arg in cmdline: /home2/ofekafsc/public_html/cgi-bin/wd.py

It does not find the serverListener.py script, even though it is launched for the first time from this script.

I think it might have something to do with Users and Permissions at the server, but since I never call the script manually, I don't see a reason for that to be the problem.

Any help will be gratefully received.

0 Answers
Related