Python process.teminate不起作用

时间:2016-12-01 18:59:57

标签: python multiprocessing

为什么终止后进程仍然存在? TimeoutProcess 是从进程派生的类,并不会使terminate方法重载。

p = TimeoutProcess(target=fn, args=args, kwargs=kwargs)
p.start()
p.join(self.timeout_duration)
if p.is_alive():
    p.terminate()
    time.sleep(0.1)
    print(p, p.is_alive())
    raise TimeoutError
if p.exception:
    raise p.exception

这是输出

(TimeoutProcess(TimeoutProcess-1,已启动),True)

1 个答案:

答案 0 :(得分:0)

terminate函数通过信号(SIGTERM)向进程发出异步终止请求。

您仍需要等待终止并使用join方法收集退出状态。

p = TimeoutProcess(target=fn, args=args, kwargs=kwargs)
p.start()
p.join(self.timeout_duration)
if p.is_alive():
    p.terminate()
    p.join(10)  # wait for process to correctly terminate
    if p.is_alive():  # in corner cases it might still happen
        raise TimeoutError
if p.exception:
    raise p.exception

如果仍然遇到TimeoutError,子进程可能会吞下SIGTERM请求。

原因可能是:SIGTERM的默认行为已被覆盖(信号处理程序在Linux上继承)或函数fn卡在C循环中(例如,如果您使用基于ctypes的API)和Python永远无法控制实际释放资源。

可以找到处理此类问题的代码的简单示例here