python: how to kill a process tree

在使用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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值