简体   繁体   中英

kill process and its sub/co-processes by getting their parent pid by python script

i am using MULTIPROCESSING to find my requirement. And when that runs i am getting a pid(may be parent! i don't know what to call that) then co processes with their own pid and reference id of first process.

Now i need to kill all those processes BY ONLY KILLING THE FIRST PROCESS then which will be the best way to do that. THAT ALSO IN PYTHONIC WAY.

Scenario is like

  ps -ef |grep py

i am getting

  2222 0001 first.py  #0001 is os process
  4323 2222 second.py
  4324 2222 third.cgi
  4324 2222 fourth.py
  4325 2222 fifth.cgi
  4326 2222 sixth.py

  2223 0001 newfirst.py    ############new first process from another script started
  4327 2223 newsecond.cgi
  4328 2223 newthird.py
  4329 2223 newfourth.cgi

now i am killing process by (when a stop button is pressed)

 kill -6 2222   ###from terminal

then only first.py is getting killed and the remaining co-processes still running. Of course i can kill other processes from terminal,,but i want to do it in a more pythonic way(by running a script which will trigger when someone press a STOP button form front-end designed to run .py files )

Now how can i kill all those co-process as soon as i kill first.py (as i don't want its co's to run anymore) but the other newfirst.py and its co's should not get disturbed.

what i come up to is this far

import os
pid = os.getpid()   
os.system('kill -9 ' + pid)

so how to filter out co-processes from that first process id 2222 and kill them.

i have also tried using psutil,but passing name after name to kill is not very convincing.

I have checked subprocess.popen method but failed and now i am out of logic,please suggest.

If any other info is needed,please do comment.

From your question, I am not able to understand; however I am assuming that you have process id handy eg in your example, you have process id 2222. Then you can try this:

#Assuming you have parent_pid i.e. from your example you have 2222
pname = psutil.Process(parent_pid)
cpid = pname.get_children(recursive=True)
for pid in cpid:
    os.kill(pid.pid, signal_num) #signal_num is the signal you want to send i.e. 9 as per your example

Please take care of exception handling eg check if process/child-process exist before you kill it etc using try - except block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM