注意事项:使用xrange隐含python2
xrange(1, 4)将生成3个值而不是4(因此,只有3个子级)Note: The functions registered via this module are not called when the program is killed by a signal not handled by Python, when a Python fatal internal error is detected, or when os._exit() is called.
您不处理TERM信号(默认情况下由kill命令发送),因此主进程不调用cleanup函数(让它的子进程运行)。在
我修改了你的代码以更好地说明行为。在
代码00.py:#!/usr/bin/env python2
import sys
import multiprocessing
import os
import time
print_text_pattern = "Output from process {0:s} - pid: {1:d}, ppid: {2:d}"
def child(name):
while True:
print(print_text_pattern.format(name, os.getpid(), os.getppid()))
time.sleep(1)
def main():
procs = list()
for x in xrange(1, 3):
proc_name = "Child{0:d}".format(x)
proc = multiprocessing.Process(target=child, args=(proc_name,))
proc.daemon = True #x % 2 == 0
print("Process {0:s} daemon: {1:}".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 {0:s} {1:d}bit on {2:s}\n".format(" ".join(item.strip() for item in sys.version.split("\n")), 64 if sys.maxsize > 0x100000000 else 32, sys.platform))
main()
print("\nDone.")
注意事项:稍微改变了子进程的生成方式:所有子进程都被创建1st,然后才启动
从每个进程添加一些print调用,以跟踪它们在stdout中的活动-还添加了一些time.sleep调用(1秒),以避免产生过多的输出
最重要的是-主进程不再永远运行。在某个时候,它优雅地退出(在3个周期之后-由于counter变量),而且我前面提到的行为也会出现。
这也可以通过截取项信号(以及可以通过kill命令显式发送的其他信号)并执行清理,这样在杀死主进程时也会杀死子进程,但这更复杂
我把事情简化了一点,这样只产生了2个孩子
移动了包含在if __name__ == "__main__":条件中的main函数(用于结构)中的所有内容,因此如果导入模块,则不会生成进程
为每个子级提供不同的值proc.daemon,然后监视输出和ps -ef | grep "code00.py"输出
向childfunc添加了一个参数(name),但这仅用于显示目的
输出:[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] 64bit 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.