Python 孤儿进程与僵尸进程

孤儿进程

from multiprocessing import Process,current_process
import time,sys

def func():
    # 孤儿进程,父进程早于子进程退出
    print('子进程PID',current_process().pid)
    time.sleep(10)

    print('子进程退出')

def main():
    print('子进程PID',current_process().pid)
    p = Process(target=func)
    p.start()
    print('父进程退出')
    sys.exit()   # 退出程序
    # p.join(timeout=1)  # 如果回收失败,则不回收
    # timeout 父进程只会阻塞等待1秒常识回收子进程。
if __name__ == '__main__':
    main()
import os,time
# 父进程早于子进程退出,此时子进程一直会被1号进程回收,监控
def func():
    pid = os.fork()      #fork()会执行分割成两部分,调用一次,返回两次,且在fork()在Linux运行。

    if pid == 0:     # 子进程pid为0
        time.sleep(10)
        print('我是子进程')

    if pid > 0:      # 父进程pid为子进程的PID
        print('我是父进程,我开启的子进程PID是',pid)
if __name__ == '__main__':
    func()

僵尸进程

import time,sys
from multiprocessing import Process,current_process
def func():
    print('子进程PID',current_process().pid)
    print('子进程退出')

def main():
    print('子进程PID',current_process().pid)
    p = Process(target=func)
    p.start()
    time.sleep(10)
    print('父进程退出')
    sys.exit()   # 退出程序
    # p.join(timeout=1)  # 如果回收失败,则不回收
    # timeout 父进程只会阻塞等待1秒常识回收子进程。
if __name__ == '__main__':
    main()

# 注:在Linux中查看进程,Z+,代表僵尸进程    ps -aux|grep python

猜你喜欢

转载自www.cnblogs.com/xinzaiyuan/p/12507572.html