Notes:
事情并不完全是这样的。该文档([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.