为什么Python中主进程退出时子进程(daemon=True)不退出?

2023-12-08

这是官方的解释daemonpython 多处理中的标志:

当进程退出时,它会尝试终止其所有守护子进程。

据我了解,父进程退出时会杀死其守护进程标志设置为 True 的子进程。

下面是我用来证明我的猜测的代码。但结果不同。

import multiprocessing


def child():
    while True:
        pass


for x in xrange(1, 4):
    proc = multiprocessing.Process(target=child, args=())
    proc.daemon=True
    proc.start()


while True:
    pass

上面启动了4个子进程和1个主进程。 我杀死了主进程,但 4 个子进程没有退出。

那么既然守护进程设置为 true,为什么它们没有被 main 终止呢?


Notes:

  • 指某东西的用途xrange暗示Python 2

  • xrange(1, 4)将产生 3 个值而不是 4 个(因此,只会有 3 个子项)

事情并不完全是这样的。该文档([Python 2.Docs]:多处理 - 守护进程)可能应该更具体。

事情是这样的多重处理注册一个清理功能杀死其所有deamonic退出时的儿童。这是通过完成的[Python 2.Docs]:atexit - 退出处理程序 (emphasis是我的):

Note:通过该模块注册的功能当程序被 Python 未处理的信号杀死时,不会调用,当检测到 Python 致命内部错误时,或者当os._exit()叫做。

你不处理TERM信号(默认由kill命令),因此主进程不会调用清理函数(使其子进程保持运行)。

我修改了您的代码以更好地说明该行为。

代码00.py:

#!/usr/bin/env python2

import multiprocessing
import os
import sys
import time


print_text_pattern = "Output from process {:s} - pid: {:d}, ppid: {:d}"


def child(name):
    while True:
        print(print_text_pattern.format(name, os.getpid(), os.getppid()))
        time.sleep(1)


def main(*argv):
    procs = list()
    for x in xrange(1, 3):
        proc_name = "Child{:d}".format(x)
        proc = multiprocessing.Process(target=child, args=(proc_name,))
        proc.daemon = True #x % 2 == 0
        print("Process {:s} daemon: {:}".format(proc_name, proc.daemon))
        procs.append(proc)

    for proc in procs:
        proc.start()

    counter = 0
    while counter < 3:
        print(print_text_pattern.format("Main", os.getpid(), os.getppid()))
        time.sleep(1)
        counter += 1


if __name__ == "__main__":
    print("Python {:s} {:03d}bit on {:s}\n".format(" ".join(elem.strip() for elem in sys.version.split("\n")),
                                                   64 if sys.maxsize > 0x100000000 else 32, sys.platform))
    rc = main(*sys.argv[1:])
    print("\nDone.\n")
    sys.exit(rc)

Notes:

  • Changed the way how children processes are spawned a bit: all of them are created 1st, and only then started

  • 添加了一些print来自每个进程的调用,以跟踪它们在StdOut- 还添加了一些睡眠时间调用(1秒),以避免产生过多的输出

  • 最重要的- 主进程不再永远运行。在某些时候它会优雅地退出(3个周期后 - 由于counter变量),然后我之前提到的行为就会出现。
    这也可以通过拦截TERM信号(以及其他可以由kill命令)然后执行清理 - 这样子进程在杀死主进程时也会被杀死 - 但这更复杂

  • 我稍微简化了一下,只生成了 2 个孩子

  • 把所有东西都搬到了一个main函数(对于结构)包含在if __name__ == "__main__":有条件的,因此如果您执行以下操作,则不会生成进程import模块

  • 赋予不同的值进程守护进程然后监控每个孩子的输出并ps -ef | grep "code00.py" output

  • 添加了一个参数(name) to child func,但这仅用于显示目的

Output:

[cfati@cfati-ubtu16x64-0:~/Work/Dev/StackOverflow]> python2 ./code00.py
Python 2.7.12 (default, Oct  8 2019, 14:14:10) [GCC 5.4.0 20160609] 064bit on linux2

Process Child1 daemon: True
Process Child2 daemon: True
Output from process Main - pid: 1433, ppid: 1209
Output from process Child1 - pid: 1434, ppid: 1433
Output from process Child2 - pid: 1435, ppid: 1433
Output from process Main - pid: 1433, ppid: 1209
Output from process Child2 - pid: 1435, ppid: 1433
Output from process Child1 - pid: 1434, ppid: 1433
Output from process Main - pid: 1433, ppid: 1209
Output from process Child1 - pid: 1434, ppid: 1433
Output from process Child2 - pid: 1435, ppid: 1433
Output from process Child1 - pid: 1434, ppid: 1433
Output from process Child2 - pid: 1435, ppid: 1433

Done.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么Python中主进程退出时子进程(daemon=True)不退出? 的相关文章

  • 蟒蛇 | MySQL | AttributeError:模块“mysql.connector”没有属性“connect”

    我正在学习 python 中的一个新库 mysql 我尝试执行以下命令 import mysql connector mydb mysql connector connect host localhost user root passwd
  • 获取 .wav 文件长度或持续时间

    我正在寻找一种方法来找出 python 中音频文件 wav 的持续时间 到目前为止我已经了解了 pythonwave图书馆 mutagen pymedia pymad我无法获取 wav 文件的持续时间 Pymad给了我持续时间 但它不一致
  • 从文本文件中删除特定字符

    我对 Python 和编码都很陌生 我当时正在做一个小项目 但遇到了一个问题 44 1 6 23 2 7 49 2 3 53 2 1 68 1 6 71 2 7 我只需要从每行中删除第三个和第六个字符 或者更具体地说 从整个文件中删除 字符
  • 在python中将数据库表写入文件的最快方法

    我正在尝试从数据库中提取大量数据并将其写入 csv 文件 我正在尝试找出最快的方法来做到这一点 我发现在 fetchall 的结果上运行 writerows 比下面的代码慢 40 with open filename a as f writ
  • 如何返回 cost, grad 作为 scipy 的 fmin_cg 函数的元组

    我怎样才能使 scipy 的fmin cg使用一个返回的函数cost and gradient作为元组 问题是有f对于成本和fprime对于梯度 我可能必须执行两次操作 非常昂贵 grad and cost被计算 此外 在它们之间共享变量可
  • 按边距(“全部”)值列对 Pandas 数据透视表进行排序

    我试图根据 pandas 数据透视表中的行总和对最后一列 边距 aggrfunc 进行降序排序 我知道我在这里错过了一些简单的东西 但我无法弄清楚 数据框 数据透视表 WIDGETS DATE 2 1 16 2 2 16 2 3 16 Al
  • 在Python中从大文件中搜索单词列表

    我是新蟒蛇 我有一个单词列表和一个非常大的文件 我想删除文件中包含单词列表中的单词的行 单词列表按排序给出 并且可以在初始化期间输入 我正在努力寻找解决这个问题的最佳方法 我现在正在进行线性搜索 这花费了太多时间 有什么建议么 您可以使用i
  • Series.sort() 和 Series.order() 有什么区别?

    s pd Series nr randint 0 10 5 index nr randint 0 10 5 s Output 1 3 7 6 2 0 9 7 1 6 order 按值排序并返回一个新系列 s order Output 2 0
  • 如何过滤 Pandas GroupBy 对象并获取 GroupBy 对象?

    当对 Pandas groupby 操作的结果执行过滤时 它返回一个数据帧 但假设我想执行进一步的分组计算 我必须再次调用 groupby 这似乎有点绕 有更惯用的方法吗 EDIT 为了说明我在说什么 我们无耻地从 Pandas 文档中窃取
  • 协程从未被等待

    我正在使用一个简单的上下文管理器 其中包含一个异步循环 class Runner def init self self loop asyncio get event loop def enter self return self def e
  • 使用python从gst管道抓取帧到opencv

    我在用着OpenCV http opencv org 和GStreamer0 10 我使用此管道通过自定义套接字通过 UDP 接收 MPEG ts 数据包sockfd由 python 提供并显示它xvimagesink 而且效果很好 以下命
  • 使用 for 循环创建一系列元组

    我已经搜索过 但找不到答案 尽管我确信它已经存在了 我对 python 很陌生 但我以前用其他语言做过这种事情 我正在以行形式读取数据文件 我想将每行数据存储在它自己的元组中 以便在 for 循环之外访问 tup i inLine wher
  • pandas 相当于 np.where

    np where具有向量化 if else 的语义 类似于 Apache Spark 的when otherwise数据帧方法 我知道我可以使用np where on pandas Series but pandas通常定义自己的 API
  • 是否需要关闭没有引用它们的文件?

    作为一个完全的编程初学者 我试图理解打开和关闭文件的基本概念 我正在做的一项练习是创建一个脚本 允许我将内容从一个文件复制到另一个文件 in file open from file indata in file read out file
  • 为什么 __dict__ 和 __weakref__ 类从未在 Python 中重新定义?

    类创建似乎从来没有re 定义 dict and weakref class属性 即 如果它们已经存在于超类的字典中 则它们不会添加到其子类的字典中 但始终re 定义 doc and module class属性 为什么 gt gt gt c
  • 使用 PIL 在 Tkinter 中显示动画 GIF

    我正在尝试制作一个程序来使用 Tkinter 显示动画 GIF 这是我最初使用的代码 from future import division Just because division doesn t work right in 2 7 4
  • 无法通过 Python 子进程进行 SSH

    我需要通过堡垒 ssh 进入机器 因此 该命令相当长 ssh i
  • minizinc python 安装

    我通过 anaconda 提示符在 python 上安装了 minizinc 就像其他软件包一样 pip install minizinc 该软件包表示已成功安装 我可以导入该模块 但是 我正在遵循基本示例https minizinc py
  • 如何获取pandas中groupby对象中的组数?

    我想知道有多少个独特的组需要执行计算 给定一个名为 groupby 的对象dfgroup 我们如何找到组的数量 简单 快速 Pandaic ngroups 较新版本的 groupby API pandas gt 0 23 提供了此 未记录的
  • 如何(安全)将 Python 对象发送到我的 Flask API?

    我目前正在尝试构建一个 Flask Web API 它能够在 POST 请求中接收 python 对象 我使用 Python 3 7 1 创建请求 使用 Python 2 7 运行 API 该 API 设置为在我的本地计算机上运行 我试图发

随机推荐