Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ted-dev-42/bd19224a4b6cc79470118337cc3bdc8b to your computer and use it in GitHub Desktop.
Save ted-dev-42/bd19224a4b6cc79470118337cc3bdc8b to your computer and use it in GitHub Desktop.
kill process and it's subprocesses
import subprocess
import psutil
def kill_proc_and_sub(pid):
print("kill proc and all it's subprocesses: {}".format(pid))
try:
parent_process = psutil.Process(pid)
except Exception as ex:
print("kill proc failed: " + ex.message)
return
# plist = []
# for p in parent_process.children(recursive=True):
# plist.append(p)
parent_process.suspend()
for p in parent_process.children(recursive=True):
try:
print("kill sub: {}:{} ".format(p.name(), p.pid))
p.terminate()
except psutil.NoSuchProcess as ex:
print("kill sub proc fail, no such process: " + str(ex.message))
except Exception as e:
print("kill sub: {}:{} failed".format(p.name, p.pid))
print(e)
print("kill parent: " + parent_process.name())
try:
parent_process.kill()
except Exception:
print("kill parent proc: {} failed".format(parent_process.name))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment