day29-1 守护进程
守护进程
守护进程会在主进程代码执行结束后和主进程一起终止
# 守护进程
import time
from multiprocessing import Process
def task1():
print('son1 process run:', time.ctime())
time.sleep(3)
print('son1 process stop:', time.ctime())
def task2():
print('son2 process run:', time.ctime())
time.sleep(5)
print('son2 process stop:', time.ctime())
if __name__ == '__main__':
p1 = Process(target=task1)
p2 = Process(target=task2)
p1.daemon = True # 将p1子进程设为主进程的守护进程,必须要写在开启该子进程的前面
p1.start() # 开启进程p1
p2.start() # 开启进程p2
time.sleep(1)
print('parent process stop:', time.ctime())
-----------------------------------------------------------------
son2 process run: Wed Jul 3 15:34:43 2019
son1 process run: Wed Jul 3 15:34:43 2019
parent process stop: Wed Jul 3 15:34:44 2019 # 在子进程结束时,p1子进程跟着结束,所以son1 process stop不打印
son2 process stop: Wed Jul 3 15:34:48 2019
守护进程内无法再开启子进程,否则抛出异常:AssertionError: daemonic processes are not allowed to have children
# 在守护进程内开启子进程,抛出异常:AssertionError: daemonic processes are not allowed to have children
import time
from multiprocessing import Process
def task11():
print('son son process:', time.ctime())
def task1():
p11 = Process(target=task11)
p11.start()
if __name__ == '__main__':
p1 = Process(target=task1)
p1.daemon = True
p1.start()
time.sleep(1)
print('parent process stop:', time.ctime())
-----------------------------------------------------------------------------
Process Process-1:
Traceback (most recent call last):
File "C:\Python3\lib\multiprocessing\process.py", line 258, in _bootstrap
self.run()
File "C:\Python3\lib\multiprocessing\process.py", line 93, in run
self._target(*self._args, **self._kwargs)
File "E:\python9\day32\test.py", line 16, in task1
p11.start()
File "C:\Python3\lib\multiprocessing\process.py", line 103, in start
'daemonic processes are not allowed to have children'
AssertionError: daemonic processes are not allowed to have children
parent process stop: Wed Jul 3 15:42:33 2019
# 不设守护进程,在子进程内开启子进程.类似于一种嵌套
import time
from multiprocessing import Process
def task11():
print('son1 son process:', time.ctime())
def task1():
p11 = Process(target=task11)
p11.start()
time.sleep(1)
print('son process:',time.ctime())
if __name__ == '__main__':
p1 = Process(target=task1)
p1.start()
time.sleep(1)
print('parent process stop:', time.ctime())
-----------------------------------------------------------------------------
son1 son process: Wed Jul 3 15:48:34 2019
parent process stop: Wed Jul 3 15:48:34 2019
son process: Wed Jul 3 15:48:35 2019