gpt4 book ai didi

python - 如何使用 python fork 避免失效进程?

转载 作者:行者123 更新时间:2023-12-05 03:10:47 26 4
gpt4 key购买 nike

在 python3 中,我正在创建 fork 的子进程,我认为我正确地退出了它。这是一些代码示例:

import os

child_pid = os.fork()
if child_pid == 0:
print("I am in the child with PID "+str(os.getpid()))
# doing something
a = 1+1
print("Ending child with PID "+str(os.getpid()))
os._exit(0)
else:
#parent process
os.waitpid(-1, os.WNOHANG)
import time
for x in range(100):
time.sleep(1)
print("waiting...")

现在,由于子进程似乎已经结束,它仍然可以被视为一个“已失效”进程(而父进程仍在运行)。如何真正摆脱那个结束的子进程?如何更改代码?

最佳答案

如果你不想让 parent 等待,你可以使用双叉习语。 (参见 What is the reason for performing a double fork when creating a daemon?)

基本思想是父进程(称其为 P)派生一个子进程(C1),该子进程立即再次派生以创建另一个子进程(C2 ) 然后退出。在这种情况下,由于 C2 的父进程已死,init 进程将继承 C2 并为您等待。您仍然需要在 P 进程中等待 C1,否则 C1 将成为僵尸。但是,C1 只运行了很短的时间,所以 P 进程不会等待很长时间。运行 C2 的代码可以根据需要花费任意多的时间,而不关心它是在 P 之前还是之后完成。

另一个想法是处理在子进程退出时发生的 SIGCHILD 信号。来自 https://mail.python.org/pipermail/tutor/2003-December/026748.html

import os,signal

def handleSIGCHLD():
os.waitpid(-1, os.WNOHANG)

signal.signal(signal.SIGCHLD, handleSIGCHLD)

关于python - 如何使用 python fork 避免失效进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38775178/

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