阅读背景:

进程,互斥锁,生产者消费者,线程

来源:互联网 

进程,互斥锁,生产者消费者,线程

一、僵尸进程与孤儿进程

  • 代码演示
'''
僵尸进程(有坏处):
    - 在子进程结束后,主进程没有正常结束,子进程的PID不会被回收。

    缺点:
        - 操作系统中PID号是有限的,比如子进程PID号无法正常回收,则会占用PID号。
        - 资源浪费
        - 若PID号满了,则无法创建新的进程。

孤儿进程(没有坏处):

    - 在子进程没有结束时,主进程没有“正常结束”,子进程PID不会被回收。
    - 操作系统优化机制(孤儿院):
        当主进程意外终止,操作系统会检测是否有正在运行的子进程,会将他们放入孤儿院,让操作系统帮你自动回收。

'''
#孤儿院进程
from multiprocessing import Process
from multiprocessing import current_process
#在子进程中调用,可以拿到子进程对象.pid可以获取pid号
#在主进程中调用,可以拿到主进程对象.pid可以获取pid号
import os
import time


def task():
    print(f'start...{current_process().pid}')
    time.sleep(1000)
    print(f'end...{os.getpid()}')
    print('子进程结束啦啊...')

if __name__ == '__main__':
    p = Process(target=task)

    p.start()

    print(f'进入主进程的io--->{current_process().pid}')
    time.sleep(4)
    print(f'进入主进程的io--->{os.getpid()}')

    #主进程结束
    print('主进程结束...')
    print(f'查看主进程{os.getpid()}')
    f = open('yafenghandsome.txt')#此时主进程没有正常结束


#僵尸进程
from multiprocessing import Process
from multiprocessing import current_process
#在子进程中调用,可以拿到子进程对象.pid可以获取pid号
#在主进程中调用,可以拿到主进程对象.pid可以获取pid号
import os
import time
def task():
    print(f'start...{current_process().pid}')
    time.sleep(1)
    print(f'end...{os.getpid()}')
    print('子进程结束啦啦...~~~')

if __name__ == '__main__':
    p = Process(target=task)

    p.start()

    print(f'进入主进程的io--->{current_process().pid}')
    time.sleep(5)
    print(f'进入主进程的io--->{os.getpid()}')

    print('主进程结束...')
    print(f'查看主主进程{os.getppid()}')
    f = open('yafeng6666.txt')'



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: