Python 子进程清理机制与僵尸进程成因解析

拾柒
拾柒
发布时间:2026-10-14 | 2人浏览过
原创

本文深入剖析 Python multiprocessing 模块中子进程的自动清理机制。通过源码分析 _cleanup 函数的执行时机,解释了为何在持续创建子进程的场景下,系统中会始终存在一个僵尸进程。重点解析 _children 集合管理与 os.waitpid 回收逻辑的关系,帮助开发者理解 Python 对子进程资源的后台处理策略。

Python 子进程清理机制与僵尸进程成因解析

起步

通常认为 Python 会自动清理已完成任务的子进程,但实际测试中确实观察到了僵尸进程的存在。


import multiprocessing as mp
import os
import time
def pro():
 print ("os.pid is ", os.getpid())
if __name__ == '__main__':
 print ("parent ", os.getpid())
 while True:
  p = mp.Process(target = pro)
  p.start()
  time.sleep(1)

因此,有必要重新梳理这一过程的内部逻辑。

销毁僵尸进程的时机

在文件 Lib/multiprocessing/process.py 中,Multiprocessing.Process 类继承自 BaseProcess。查看其 start 方法的实现:


_children = set()
class BaseProcess(object):
 def start(self):
  self._check_closed()
  _cleanup()
  self._popen = self._Popen(self)
  self._sentinel = self._popen.sentinel
  # Avoid a refcycle if the target function holds an indirect
  # reference to the process object (see bpo-30775)
  del self._target, self._args, self._kwargs
  _children.add(self)

_children 是一个全局集合变量,用于保存所有 BaseProcess 实例。在 start 函数末尾,通过 _children.add(self) 将当前进程对象加入该集合。同时注意到 _cleanup() 函数的定义:


def _cleanup():
 # check for processes which have finished
 for p in list(_children):
  if p._popen.poll() is not None:
   _children.discard(p)

_popen 是一个 Popen 对象,其代码位于 multiprocessing/popen_fork.py 中。该类的 poll 函数内部调用了 id, sts = os.waitpid(self.pid, flag),这是一个用于回收子进程的系统调用。回收完成后,会将对应的 BaseProcess 子类实例从 _children 集合中移除。

至此逻辑清晰:Python 在子进程 start 时将其加入集合。由于子进程可能长时间运行,集合中会积累不同状态的进程。为防止过多僵尸进程占用资源,Python 选择在下一个子进程 start 时执行清理操作。这意味着,最后一个子进程在自身程序运行完毕后变为僵尸进程,它需等待下一个子进程 start 触发清理才被回收。因此,ps 命令中总能看到一个僵尸进程,但其进程 ID 会随新进程的创建而不断变化。

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表