gpt4 book ai didi

python multiprocessing.Process.terminate - 如何杀死子进程

转载 作者:太空宇宙 更新时间:2023-11-04 02:57:32 25 4
gpt4 key购买 nike

这段代码:

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 , 但如何杀死已杀死进程的子进程?

一个可能的想法可能是:

  • 在 try/except block 中包装 WorkerProcess.run() 方法以捕获 SIGTERM,并终止 subprocess.call 调用。但是我不确定如何在 WorkerProcess 中捕获 SIGTERM

  • 我也尝试在 WorkerProcess 中设置 signal.signal(signal.SIGINT, handler),但我得到了 ValuError,因为它只允许在主线程中设置。

我现在该怎么办?

最佳答案

编辑:正如@svalorzen 在评论中指出的那样,这实际上不起作用,因为对 self.subprocess 的引用丢失了。


终于找到了一个干净、可接受的解决方案。由于 mp.Process.terminate 是一个方法,我们可以覆盖它。

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()

# HERE
def terminate(self):
self.subprocess.terminate()
super(WorkerProcess, self).terminate()

关于python multiprocessing.Process.terminate - 如何杀死子进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41938405/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com