[英]How to kill a process within a thread in python?
好的,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
並釋放以繼續執行線程......或者如果有更好的解決方案。 任何幫助將不勝感激 !!
您可以使用Popen
對象的terminate
(graceful)和kill
方法來terminate
您創建的進程。 像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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.