此代码:蟒蛇multiprocessing.Process.terminate - 如何杀死子进程
import multiprocessing as mp
from threading import Thread
import subprocess
import time
class WorkerProcess(mp.Process):
def run(self):
# Simulate long running task
self.subprocess = subprocess.Popen(['python', '-c', 'import time; time.sleep(1000)'])
self.code = self.subprocess.wait()
class ControlThread(Thread):
def run():
jobs = []
for _ in range(2):
job = WorkerProcess()
jobs.append(job)
job.start()
# wait for a while and then kill jobs
time.sleep(2)
for job in jobs:
job.terminate()
if __name__ == "__main__":
controller = ControlThread()
controller.start()
当我终止催生WorkerProcess实例。他们死得很好,但子进程python -c 'import time; time.sleep(1000)
运行,直到完成。这是well documented in the official docs,但我该如何杀死死亡进程的子进程?
甲possbile soultion可能是:
裹WorkerProcess.run()内的try /方法除了块捕捉SIGTERM,并终止
subprocess.call call
。但我不知道如何捕捉工人进程中的SIGTERM我也尝试在WorkerProcess中设置
signal.signal(signal.SIGINT, handler)
,但我得到ValuError,因为它只允许在主线程中设置。
现在我该怎么办?
嗨,对不起,谢谢你的回答,但我想避免使用队列。根据正确结束的例子,你是对的。这仅仅是一个虚拟的例子,用来说明工作流程,它(idk为什么)有效(不明智的选择,我同意)。在我的真实情况下,这个过程只是继续运行 –