somepeople

python中的守护进程

守护进程:

1.伴随父进程的生命周期终结而终结的进程

2.守护进程内不允许再开子进程

def func1():
    print('func1')

def func2():
    print('func2')
if __name__ == '__main__':
    from multiprocessing import Process
    p1 = Process(target=func1)
    p2 = Process(target=func2)
    p1.daemon = True
    p1.start()
    p2.start()
    print('master over')
#master over  p1伴随父进程的终结而终结,基本是没有开始运行就结束了
#func2

 守护进程中再开启子进程会报错:

from multiprocessing import Process
import time
def task(name):
    print('%s process start'%name)
    time.sleep(3)
    p = Process(target=time.sleep,args=(3,))
    p.start()
    print('%s process end'%name)
if __name__ == '__main__':
    p = Process(target=task,args=('子进程',))
    p.daemon = True
    p.start()
    p.join()
    print('main')
#

子进程 process start
Process Process-1:
Traceback (most recent call last):
File "C:\Users\wangwenchao\AppData\Local\Programs\Python\Python38\lib\multiprocessing\process.py", line 315, in _bootstrap
self.run()
File "C:\Users\wangwenchao\AppData\Local\Programs\Python\Python38\lib\multiprocessing\process.py", line 108, in run
self._target(*self._args, **self._kwargs)
File "E:\pythondir\a.py", line 7, in task
p.start()
File "C:\Users\wangwenchao\AppData\Local\Programs\Python\Python38\lib\multiprocessing\process.py", line 118, in start
assert not _current_process._config.get('daemon'), \
AssertionError: daemonic processes are not allowed to have children
main

 守护进程&&守护线程:

守护进程当主进程程序执行完毕后,守护进程随之结束

守护线程当主进程内其他非守护进程结束完后而结束

posted on 2020-12-08 20:56  Hello_Thanos  阅读(810)  评论(0编辑  收藏  举报

导航