gpt4 book ai didi

python - python进程如何知道何时退出?

转载 作者:行者123 更新时间:2023-11-28 17:48:25 25 4
gpt4 key购买 nike

当您执行 python 脚本时,进程/解释器是否会因为从脚本中读取 EOF 字符而退出? [IE。那是退出信号吗?]

接下来是 python 子进程如何/何时知道退出,即当您通过覆盖 run() 方法启动子进程时,如下所示:

class Example(multiprocessing.Process):
def __init__(self, task_queue, result_queue):
multiprocessing.Process.__init__(self)
self.task_queue = task_queue
self.result_queue = result_queue

def run(self):
while True:
next_task = self.task_queue.get()
if next_task is None:
print '%s: Exiting' % proc_name
break
#more stuff...[assume there's some task_done stuff, etc]

if __name__ == '__main__':
tasks = multiprocessing.JoinableQueue()
results = multiprocessing.Queue()

processes = [ Example(tasks, results)
for i in range(5) ]
for i in processes:
i.start()
#more stuff...like populating the queue, etc.

现在,我很好奇的是:子进程是否会在 run() 方法完成后自动退出?而如果我在执行过程中杀死了主线程,子进程会不会立即结束?如果他们的 run() 调用可以独立于父进程的状态完成,他们会结束吗?

最佳答案

是的,每个子进程在 run 方法完成后自动终止,尽管我认为您应该避免子类化 Process 并使用 target 改为参数。

请注意,在 linux 中,如果您不读取退出状态,子进程可能会保持僵尸状态:

>>> from multiprocessing import Process
>>> def target():
... print("Something")
...
>>> Process(target=target).start()
>>> Something

>>>

如果我们看一下这之后的过程:

enter image description here

如果我们读取进程的退出状态(使用 Process.exitcode),则不会发生这种情况。

每个 Process 实例在后台启动一个新进程,该子进程如何以及何时终止取决于操作系统。每个操作系统都提供了一些进程之间的通信方式。如果您终止“父”进程,子进程通常不会终止。

例如这样做:

>>> from multiprocessing import Process
>>> import time
>>> def target():
... while True:
... time.sleep(0.5)
...
>>> L = [Process(target=target) for i in range(10)]
>>> for p in L: p.start()
...

主 python 进程将有 10 个子进程:

enter image description here

现在,如果我们终止该进程,我们将获得:

enter image description here请注意子进程如何被 init 继承并仍在运行。

但是,正如我所说,这是特定于操作系统的。在某些操作系统上,终止父进程将终止所有子进程。

关于python - python进程如何知道何时退出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14423826/

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