概述
Tutorial解释:
daemon
-
The process’s daemon flag, a Boolean value. This must be set before
start()
is called.The initial value is inherited from the creating process.
When a process exits, it attempts to terminate all of its daemonic child processes.
Note that a daemonic process is not allowed to create child processes. Otherwise a daemonic process would leave its children orphaned if it gets terminated when its parent process exits. Additionally, these are not Unix daemons or services, they are normal processes that will be terminated (and not joined) if non-daemonic processes have exited.
在脚本的运行过程中,可以设置子进程对象的daemon属性:
p.daemon = True: 主进程运行完不会检查子进程的状态(是否执行完),直接结束进程;
p.daemon = False: 主进程运行完先检查子进程的状态(是否执行完),子进程执行完后,直接结束进程;
daemon默认值为False
实例1:
1 #!/usr/bin/python3 2 3 from time import sleep 4 import multiprocessing as mp 5 import time 6 import os 7 8 def main(sec): 9 sleep(sec) 10 print("Child process start") 11 sleep(sec) 12 13 14 p = mp.Process(name = "child", target = main, args = (10,)) 15 p.daemon = True 16 17 print("Main process", os.getpid()) 18 p.start() 19 print("child PID:", p.pid) 20 print("-----------------") 21 print("End")
测试结果为:
Main process 28747
child PID: 28748
-----------------
End
主进程未检查main()生成的子进程对象状态直接结束
实例2:
#!/usr/bin/python3 from time import sleep import multiprocessing as mp import time import os def main(sec): sleep(sec) print("Child process start") sleep(sec) p = mp.Process(name = "child", target = main, args = (10,)) #p.daemon = True print("Main process", os.getpid()) p.start() print("child PID:", p.pid) print("-----------------") print("End")
测试结果为:
Main process 28785
child PID: 28786
-----------------
End
Child process start
只是注释掉#p.daemon = True, 系统默认子进程对象daemon属性为False,主进程会检查子进程状态,等子进程结束后再退出;
PS.个人感觉daemon方法与p.join()阻塞函数类似
转载于:https://www.cnblogs.com/Darren-Dai/p/8551813.html
最后
以上就是忧郁香烟为你收集整理的进程的daemon属性的全部内容,希望文章能够帮你解决进程的daemon属性所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复