Killing process with python

Viewed 39

I'm trying to kill recent processes that start AFTER my program starts, after a condition, the program will keep running continuously, but it has only killed the processes that started BEFORE the program ran, if I run it first, and then open something nothing happens, can anyone help me? I've tried several things and I end up in the same place, thank you very much. (OS = LINUX) (sorry for bad english, i'm still learning)

p = psutil.pids()

for x in p:
       s = psutil.Process(x)
       tempo_processos = datetime.datetime.fromtimestamp(s.create_time()).strftime("%H%M%S")
       if int(time.strftime("%H%M%S")) - int(tempo_processos) < 500:  #get the current time taking the time that the process was started to get the shortest possible time
            if s.name() == 'python3':
               pass
            else:
              os.popen(f"kill -9 {x}")
                                
    

1 Answers

psutil.pids gets the PIDs of the processes running when the code is executing, so any processes started after you code started wouldn't be returned by psutil.pids and, therefore, can't be killed.

You can try something like this:

while True:
    p = psutil.pids()
    kill processes
    wait(some time)

Related