0

in my script i am getting a process id(parent/main)

for that main process id 3-4 several sub processes are running in linux terminal

My requirement is from that processid killing all sub process and sub processes also.

i have tried

 import os
 pid = parent process id
 from  subprocess import call
 call(["pkill", "-TERM","-P", str(pid)])

But not successfull at doing that.

Also tried

 os.system('kill -9 ' + pid)  # only parent is getting killed subpid are still running.

Please suggest something like list out all sub process by their main process id.then in loop how to kill those and then the parent process.

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

Sadly this was not helpful in my case.

Community
  • 1
  • 1
Satya
  • 5,470
  • 17
  • 47
  • 72
  • @JohnZwinck-does not help either. – Satya Dec 17 '15 at 10:15
  • 3
    Why doesn't it help ? What's specific issues do you have with those solutions ? – Mel Dec 17 '15 at 10:23
  • @Satya: I think the first step you need to pursue is to "create a process group" which contains all the processes you wish to kill later on. In other words, it's not just how to solve this problem in Python, but also making the problem itself disappear by using process groups which are the conventional way to solve this problem on *nix systems. – John Zwinck Dec 17 '15 at 10:29

1 Answers1

0

Use psutil to do that.

import signal
import psutil

def kill(ppid, signal=signal.SIGTERM):
    try:
      process = psutil.Process(ppid)
    except psutil.NoSuchProcess:
      return
    pids = process.get_children(recursive=True)
    for pid in pids:
      os.kill(pid.pid, signal)
Kenly
  • 24,317
  • 7
  • 44
  • 60