如何杀死线程中调用的系统进程

时间:2014-08-27 07:24:23

标签: python python-2.7 ubuntu

我在一个帖子中调用top进程。

如何在其他过程完成后或在一段时间后杀死线程和顶级进程?

class ExternalProcess(threading.Thread):   
    def run(self):
        os.system("top")


def main():

    # run the thread and 'top' process here

    # join all other threads
    for thread in self.thread_list:
        thread.join()

    # stop the thread and 'top' process here

2 个答案:

答案 0 :(得分:0)

如果您使用的是类Unix平台,可以使用ps -A列出您的流程,请尝试以下操作:

import subprocess, signal
import os
def killproc(procname):
 p = subprocess.Popen(['ps', '-A'], stdout=subprocess.PIPE)
 out, err = p.communicate()
 for line in out.splitlines():
   if procname in line:
    pid = int(line.split(None, 1)[0])
    os.kill(pid, signal.SIGKILL)

killproc('firefox') #this is an example 

如果您不在unix中使用正确的命令而不是ps -A

答案 1 :(得分:0)

使用进程组来处理子进程,因此您可以向子进程发送信号kill。

导入操作系统 进口信号 导入子流程

class ExternalProcess(threading.Thread):   
    def run(self):
        # The os.setsid() is passed in the argument preexec_fn so
        # it's run after the fork() and before  exec() to run the shell. 
        proc = subprocess.Popen("top", stdout=subprocess.PIPE, shell=True, preexec_fn=os.setsid) 

        os.killpg(proc.pid, signal.SIGTERM)  # Send the signal to all the process groups

def main():

    # run the thread and 'top' process here

    # join all other threads
    for thread in self.thread_list:
        thread.join()

    # stop the thread and 'top' process here
相关问题