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()阻塞函數類似