I am trying to find if the process is running based on process id. The code is as follows based on one of the post on the forum. I cannot consider process name as there are more than one process running with the same name.
def findProcess( processId ): ps= subprocess.Popen("ps -ef | grep "+processId, shell=True, stdout=subprocess.PIPE) output = ps.stdout.read() ps.stdout.close() ps.wait() return output def isProcessRunning( processId): output = findProcess( processId ) if re.search(processId, output) is None: return true else: return False
Output :
1111 72312 72311 0 0:00.00 ttys000 0:00.00 /bin/sh -c ps -ef | grep 71676 1111 72314 72312 0 0:00.00 ttys000 0:00.00 grep 71676
It always return true as it can find the process id in the output string.
Any suggestions? Thanks for any help.
wait() return output # This is the function you can use def isThisRunning( process_name ): output = findThisProcess( process_name ) if re.search('path/of/process'+process_name, output) is None: return False else: return True # Example of how to use if isThisRunning('some_process') == False: print("Not running") else: ...
Bash commands to check running process: pgrep command – Looks through the currently running bash processes on Linux and lists the process IDs (PID) on screen. pidof command – Find the process ID of a running program on Linux or Unix-like system.
You need to use the ps command. It provides information about the currently running processes, including their process identification numbers (PIDs). Both Linux and UNIX support the ps command to display information about all running process.
Try:
os.kill(pid, 0)
Should succeed (and do nothing) if the process exists, or throw an exception (that you can catch) if the process doesn't exist.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With