gpt4 book ai didi

Python 多处理 : What is the better implementation to terminate daemon process when the parent process terminated?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:08:04 25 4
gpt4 key购买 nike

我在 Ubuntu 上使用 Python 3.6 的多处理来处理与另一台设备的更快通信。

我设置 daemon = True 以在父进程完成时终止子进程。但是,当主进程终止时,另一个进程(以下代码中的_another_process)有时不会终止并继续存在。然后,当我再次运行相同的程序时,在运行上述代码时出现 address already in use 错误。当然,我可以杀死这个进程,但它很烦人,我想解决。

Class Xxx
def __init__(self):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.settimeout(2.5)
self.sock.bind((self.ip, self.port))
self.sock.settimeout(None)
self.start_process()
time.sleep(1.5)

def start_process(self):
p = mp.Process(target=self._another_process)
time.sleep(1)
p.daemon = True
p.start()

def _another_process(self):
while True:
# Do continuous (infinite) operation

我不知道为什么有时终止有时不终止,但有没有更好的实现来实现我想要的?或者,daemon = True 是最好的方法吗?

我相信我不应该使用 join() 因为我的子进程有一个无限操作,但如果我误解了,请告诉我。

最佳答案

来自 python3 文档,main 的析构函数中的 process.terminate():

p.start()
打印(p,p.is_alive())
p.terminate()

这将发送 SIGTERM 信号以供子进程处理。或者,使用 p.kill() 发送 SIGKILL。

完整示例位于 https://docs.python.org/3/library/multiprocessing.html

关于如何在您的应用程序中处理 SIGTERM: How to process SIGTERM signal gracefully?

关于Python 多处理 : What is the better implementation to terminate daemon process when the parent process terminated?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42591540/

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