Skip to main content
 首页 » 编程设计

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

2024年10月01日23cloudgamer

这段代码:

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