python僵尸进程产生的原因

 更新时间:2017年07月21日 08:54:27   作者:Huang Huang  
这篇文章主要给大家讲解的是在Python中是如何产生僵尸进程的,以及如何清除僵尸进程的方法,有需要的小伙伴可以参考下

在 unix 或 unix-like 的系统中,当一个子进程退出后,它就会变成一个僵尸进程,如果父进程没有通过 wait 系统调用来读取这个子进程的退出状态的话,这个子进程就会一直维持僵尸进程状态。

Zombie process - Wikipedia 中是这样描述的:

On Unix and Unix-like computer operating systems, a zombie process or defunct process is a process that has completed execution (via the exit system call) but still has an entry in the process table: it is a process in the "Terminated state". This occurs for child processes, where the entry is still needed to allow the parent process to read its child's exit status: once the exit status is read via the wait system call, the zombie's entry is removed from the process table and it is said to be "reaped". A child process always first becomes a zombie before being removed from the resource table. In most cases, under normal system operation zombies are immediately waited on by their parent and then reaped by the system – processes that stay zombies for a long time are generally an error and cause a resource leak.

并且僵尸进程无法通过 kill 命令来清除。

本文将探讨如何手动制造一个僵尸进程以及清除僵尸进程的办法。

手动制造一个僵尸进程

为了便于后面讲解清除僵尸进程的方法,我们使用日常开发中经常使用的 multiprocessing 模块来制造僵尸进程(准确的来说是制造一个长时间维持僵尸进程状态的子进程):

$ cat test_a.py
from multiprocessing import Process, current_process
import logging
import os
import time

logging.basicConfig(
  level=logging.DEBUG,
  format='%(asctime)-15s - %(levelname)s - %(message)s'
)


def run():
  logging.info('exit child process %s', current_process().pid)
  os._exit(3)

p = Process(target=run)
p.start()
time.sleep(100)

测试:

$ python test_a.py &
[1] 10091
$ 2017-07-20 21:28:14,792 - INFO - exit child process 10106

$ ps aux |grep 10106
mozillazg       10126  0.0 0.0 2434836  740 s006 R+  0:00.00 grep 10106
mozillazg       10106  0.0 0.0    0   0 s006 Z   0:00.00 (Python)

可以看到,子进程 10091 变成了僵尸进程。

既然已经可以控制僵尸进程的产生了,那我们就可以进入下一步如何清除僵尸进程了。

清除僵尸进程有两种方法:

•第一种方法就是结束父进程。当父进程退出的时候僵尸进程随后也会被清除。
• 第二种方法就是通过 wait 调用来读取子进程退出状态。我们可以通过处理 SIGCHLD 信号,在处理程序中调用 wait 系统调用来清除僵尸进程。

处理 SIGCHLD 信号

子进程退出时系统会向父进程发送 SIGCHLD 信号,父进程可以通过注册 SIGCHLD 信号处理程序,在信号处理程序中调用 wait
系统调用来清理僵尸进程。 $ cat test_b.py

import errno
from multiprocessing import Process, current_process
import logging
import os
import signal
import time

logging.basicConfig(
  level=logging.DEBUG,
  format='%(asctime)-15s - %(levelname)s - %(message)s'
)


def run():
  exitcode = 3
  logging.info('exit child process %s with exitcode %s',
         current_process().pid, exitcode)
  os._exit(exitcode)


def wait_child(signum, frame):
  logging.info('receive SIGCHLD')
  try:
    while True:
      # -1 表示任意子进程
      # os.WNOHANG 表示如果没有可用的需要 wait 退出状态的子进程,立即返回不阻塞
      cpid, status = os.waitpid(-1, os.WNOHANG)
      if cpid == 0:
        logging.info('no child process was immediately available')
        break
      exitcode = status >> 8
      logging.info('child process %s exit with exitcode %s', cpid, exitcode)
  except OSError as e:
    if e.errno == errno.ECHILD:
      logging.error('current process has no existing unwaited-for child processes.')
    else:
      raise
  logging.info('handle SIGCHLD end')

signal.signal(signal.SIGCHLD, wait_child)

p = Process(target=run)
p.start()

while True:
  time.sleep(100)

效果:

$ python test_b.py &
[1] 10159
$ 2017-07-20 21:28:56,085 - INFO - exit child process 10174 with exitcode 3
2017-07-20 21:28:56,088 - INFO - receive SIGCHLD
2017-07-20 21:28:56,089 - INFO - child process 10174 exit with exitcode 3
2017-07-20 21:28:56,090 - ERROR - current process has no existing unwaited-for child processes.
2017-07-20 21:28:56,090 - INFO - handle SIGCHLD end

$ ps aux |grep 10174
mozillazg       10194  0.0 0.0 2432788  556 s006 R+  0:00.00 grep 10174

可以看到,子进程退出变成僵尸进程后,系统给父进程发送了 SIGCHLD 信号,我们在 SIGCHLD 信号的处理程序中通过 os.waitpid 调用 wait 系统调用后阻止了子进程一直处于僵尸进程状态,从而实现了清除僵尸进程的效果。

相关文章

  • Python Collections强大的数据结构工具使用实例探索

    Python Collections强大的数据结构工具使用实例探索

    这篇文章主要介绍了Python Collections强大的数据结构工具的使用实例探索,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2024-01-01
  • Python中NumPy的数组重塑

    Python中NumPy的数组重塑

    这篇文章主要介绍了Python中NumPy的数组重塑,Numpy是Python科学计算库,用于快速处理任意维度的数组,NumPy使用c语言写的,底部解除了GIL,其对数组的操作速度不在受python解释器限制<BR>
    2023-07-07
  • 基于Python实现一键获取电脑浏览器的账号密码

    基于Python实现一键获取电脑浏览器的账号密码

    发现很多人在学校图书馆喜欢用电脑占座,而且出去的时候经常不锁屏,为了让大家养成良好的习惯,本文将分享一个小程序,可以快速获取你存储在电脑浏览器中的所有账号和密码,感兴趣的可以了解一下
    2022-05-05
  • pandas温差查询案例的实现

    pandas温差查询案例的实现

    本文主要介绍了pandas温差查询案例的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-06-06
  • 解决django 新增加用户信息出现错误的问题

    解决django 新增加用户信息出现错误的问题

    今天小编就为大家分享一篇解决django 新增加用户信息出现错误的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-07-07
  • Python爬虫实战演练之采集糗事百科段子数据

    Python爬虫实战演练之采集糗事百科段子数据

    读万卷书不如行万里路,只学书上的理论是远远不够的,只有在实战中才能获得能力的提升,本篇文章手把手带你用Python采集糗事百科段子的数据,大家可以在过程中查缺补漏,提升水平
    2021-10-10
  • 机器学习经典算法-logistic回归代码详解

    机器学习经典算法-logistic回归代码详解

    这篇文章主要介绍了机器学习经典算法-logistic回归代码详解,具有一定借鉴价值,需要的朋友可以参考下。
    2017-12-12
  • 利用Python为女神制作一个专属网站

    利用Python为女神制作一个专属网站

    520不知道送什么礼物?快跟随小编一起学习一下如何利用Python语言制作一个专属的网站送给女神吧!文中的示例代码讲解详细,需要的可以参考一下
    2022-05-05
  • 分享十个Python超级好用提高工作效率的自动化脚本

    分享十个Python超级好用提高工作效率的自动化脚本

    在这个自动化时代,我们有很多重复无聊的工作要做。 想想这些你不再需要一次又一次地做的无聊的事情,让它自动化,让你的生活更轻松。本文分享了10个Python自动化脚本,希望对大家有所帮助
    2022-11-11
  • Python itertools.product方法代码实例

    Python itertools.product方法代码实例

    这篇文章主要介绍了Python itertools.product方法代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-03-03

最新评论