Python 孤儿进程 僵尸进程

孤儿进程 僵尸进程

理解
在这里插入图片描述
1.孤儿进程
若切断黑色进程部分 则它的分支进程们都将成为孤儿进程
若切断黑色进程部分 则它的分支进程们都将成为孤儿进程
代码:

import os
from time import sleep

pid = os.fork()

if pid < 0:
    print("Error")
elif pid == 0:
    sleep(1)  # 子进程延时 待父进程运行结束 则子进程变为孤儿进程
    print("Child PID:", os.getpid())
    print("Get parent PID:", os.getppid())
else:
    print("Parent PID:", os.getpid())
    print("Get child PID:", pid)

运行结果:
如图所示 子进程处查询的父进程PID发生变化 说明子进程已是孤儿进程被系统收养

2.僵尸进程

"""
僵尸进程
"""
import os

pid = os.fork()

if pid < 0:
    print("Error")
elif pid == 0:
    print("Child Process:", os.getpid())
    os._exit(0)   # 子进程强行退出
else:
    while True:
        pass

运行结果:
在命令行输入 ps -aux
根据输出的pid码可看到:tarena 23601 0.0 0.0 0 0 tty2 Z+ 23:33 0:00 [python3.6]
其中 Z+则表示该进程为僵尸进程 zombies(僵尸)

2.1 僵尸进程解决方案
在这里插入图片描述
2.1.1 通过wait函数处理僵尸进程
在这里插入图片描述
代码:

"""
wait
"""
import os

pid = os.fork()

if pid < 0:
    print("Error")
elif pid == 0:
    print("Child Process:", os.getpid())
    os._exit(1)
else:
    p, status = os.wait()
    print("PID:", p)
    print("Status:", status)
    while True:
        pass

运行结果:
Child Process: 30839
PID: 30839
Status: 256

宏函数
代码:

import os

pid = os.fork()

if pid < 0:
    print("Error")
elif pid == 0:
    print("Child Process:", os.getpid())
    os._exit(1)
else:
    p, status = os.wait()
    print("PID:", p)
    print("Status:", os.WEXITSTATUS(status))
    while True:
        pass

运行结果:
Child Process: 35032
PID: 35032
Status: 1

2.1.2 创建二级子进程
在这里插入图片描述
在这里插入图片描述
代码:

import os
from time import sleep

def f1():
    sleep(3)
    print("fun1")

def f2():
    sleep(3)
    print("fun2")

pid = os.fork()

if pid < 0:
    print("Error")
elif pid == 0:  # 如果是一级子进程
    pid_0 = os.fork()   # 创建二级子进程
    if pid_0 == 0:  # 如果是二级子进程
        f1()
    else:   # 一级子进程直接退出
        os._exit(0)
else:   # 如果是父进程
    os.wait()
    f2()

运行结果:
fun2
fun1

Process finished with exit code 0

2.1.3 通过信号处理子进程结束

在这里插入图片描述
代码:

import os
import signal

signal.signal(signal.SIGCHLD, signal.SIG_IGN)

pid = os.fork()

if pid < 0:
    print("Error")
elif pid == 0:
    print("Child Process:", os.getpid())
    os._exit(1)
else:
    while True:
        pass

运行结果:
Child Process: 46124
只需写一次 所有子进程退出都不会变成僵尸进程


版权声明:本文为weixin_55643605原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。