Home > Net >  Python monitor process by pid
Python monitor process by pid

Time:02-17

I'm looking for better idea than my or may be you can show me where I made a mistake. What I'm trying to do.

  1. I try to run process with subprocess and thread it is run good and no mistakes here found, one thing that's command in Linux has timeout.
  2. I got pid 3.Than I would like monitor proc by pid, and when it finished do some stuff
def monitor_func(my_obj):
               print(my_obj.process_pid)
               sleep(20)
               while os.kill(my_obj.process_pid, 0) is None:
                     print("proc is running")
                     try:
                         os.kill(my_obj.process_pid, 0)
                     except OSError:
                         continue
               else:
                      print("proc is stopped")

What is the problem? While loop works in infinite. os.kill(my_obj.process_pid, 0) always returns NONE Thank you in advance!

CodePudding user response:

Not sure I got you right, but I am assuming you are trying to figure out if some process is still running by PID.

The main issue with your code is the fact os.kill doesn't retrun any value, so you will always get None. So the loop will never cease.


Consider the following:

def monitor_func(pid): # no need to pass the object as we aren't using it
    print(pid)
    while True:
      try:
        os.kill(pid, 0) # 0 doesn't send any signal, but does error checks
      except OSError:
        print("Proc exited")
      else:
        print("Proc is still running")
        sleep(20)

This will mostly work assuming you are using the correct PID, and have aproporaite permissions.

  • Related