在使用subprocess模块通过subprocess.Popen()类来调用.exe文件,当程序结束后,.exe对应的子进程却不能够自动结束。下面的代码段能够实现kill进程树中的所有子进程。
import os
import signal
import psutil
def kill_proc_tree(pid, sig=signal.SIGTERM, include_parent=True,
timeout=None, on_terminate=None):
"""Kill a process tree (including grandchildren) with signal
"sig" and return a (gone, still_alive) tuple.
"on_terminate", if specified, is a callabck function which is
called as soon as a child terminates.
"""
if pid == os.getpid():
raise RuntimeError("I refuse to kill myself")
parent = psutil.Process(pid)
children = parent.children(recursive=True)
if include_parent:
children.append(parent)
for p in children:
p.send_signal(sig)
gone, alive = psutil.wait_procs(children, timeout=timeout,
callback=on_terminate)
return (gone, alive)
下面是我自己写的代码段,通过递归函数实现了对进程树的删除。
# -*- coding: utf-8 -*-
import subprocess
import os
import signal
import psutil
import time
def killProc(pid):
baseProc = psutil.Process(pid)
childrenProcList = baseProc.children(recursive=True)
for proc in childrenProcList:
if (len(proc.children(recursive=True)) == 0):
subprocess.Popen("echo ubuntu123456 | sudo -S kill "+str(proc.pid), shell=True)
#os.system("kill "+str(proc.pid))
#os.kill(proc.pid, sigsubprocess.Popen("echo ubuntu123456 | sudo -S modprobe iwlwifi connector_log=0x1", shell=True)nal.SIGTERM)
#proc.kill()
else:
killProc(proc.pid)