我是靠谱客的博主 忧郁香烟,最近开发中收集的这篇文章主要介绍进程的daemon属性,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

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属性所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(51)

评论列表共有 0 条评论

立即
投稿
返回
顶部