如何在python中删除线程内的进程?

时间:2015-03-04 17:34:15

标签: python multithreading concurrency signals

好的,A类是线程。 B级打电话。我试图杀死在线程内创建的多个进程(tor和firefox),但似乎信号只能通过主线程发送,所以它失败了,它说:

signal only works in main thread

我不太了解线程......

import subprocess
from threading import Thread

class A(Thread):

    def __init__(self):
        Thread.__init__(self)

    def run(self):
        # CREATE TWO PROCESSES
        subprocess.call(['tor'], shell=True)
        subprocess.call(['firefox'], shell=True)

        # ... stuff to get the pid of each process ...

        # KILL'EM (the failing part)
        subprocess.call(['kill -9 5431'], shell=True)
        subprocess.call(['kill -9 5432')], shell=True)

class B(object):
    def __init__(self):
        x = A()
        x.start()

if __name__ == '__main__':
    B()

我不知道是否可以用RLock完成。获取,然后用信号调用subprocess.call并释放以继续线程执行......或者是否有更好的解决方案。任何帮助将不胜感激!!

1 个答案:

答案 0 :(得分:0)

您可以使用terminate对象的kill(正常)和Popen方法来终止您创建的进程。像firefox这样的程序往往会立即返回,所以这并不总是有效。但总体思路是:

import subprocess
import threading

def kill_this(procs, hard=False):
    """kill the Popen processes in the list"""

    for proc in procs:
        if hard:
            proc.kill()
        else:
            proc.terminate()

class A(threading.Thread):
    """Runs tor and firefox, with graceful termination in 10 seconds and
    a hard kill in 20 seconds as needed"""

    def __init__(self):
        Thread.__init__(self)

    def run(self):
        # create processes
        tor = subprocess.Popen(['tor'])
        firefox = subprocess.Popen(['firefox'])

        # setup timers to kill 'em 
        soft = threading.Timer(10, kill_this, ((tor, firefox), False))
        hard = threading.Timer(20, kill_this, ((tor, firefox), True))

        # wait for process exit
        tor.wait()
        firefox.wait()

        soft.cancel()
        hard.cancel()

或者,您可以使用系统调用来获取要杀死的进程的pid,然后将kill_this转换为使用其他API:

import subprocess
import threading
import signal

def kill_this(procs, hard=False):
    """kill the process pids in the list"""

    for proc in procs:
        if hard:
            os.kill(pid, signal.SIGKILL)
        else:
            proc.terminate(pid, signal.SIGTERM)