python清理子进程机制剖析
作者:栖迟於一丘 时间:2021-08-10 22:05:19
起步
在我的印象中,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)
于是我觉得我要重新了解一下这个过程。
销毁僵尸进程的时机
mutilprossing.Process 继承自 BaseProcess 文件在 Lib/mutilprossing/process.py 中,我们看看它的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 对象,代码在 multiprossing/popen_fork.py 中,其 poll 函数有个 id, sts = os.waitpid(self.pid, flag) 一个回收子进程的函数。回收后再将 BaseProcess 子类实例从_children中移除。
这下就清楚了,python在子进程start中将进程放入集合,子进程可能长时间运行,因此这个集合上的进程会有很多状态,而为了防止过多僵尸进程导致资源占用,python会在下一个子进程 start 时清理僵尸进程。所以,最后一个子进程在自身程序运行完毕后就变成僵尸进程,它在等待下一个子进程start时被清理。所以 ps 上总有一个僵尸进程,但这个僵尸进程的 进程id 一直在变化。
来源:http://www.hongweipeng.com/index.php/archives/1375/?utm_source=tuicool&utm_medium=referral
标签:python,子进程
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
sql 存储过程批量删除数据的语句
2012-08-21 10:24:14
Oracle平台应用数据库系统的设计与开发
2010-07-21 13:03:00
利用arcgis的python读取要素的X,Y方法
2023-03-13 11:27:05
java JSP开发之Spring中Bean的使用
2023-06-16 07:35:08
![](https://img.aspxhome.com/file/2023/1/77461_0s.png)
JavaScript登录验证码的实现
2023-08-23 21:03:12
检测远程文件是否存在
2009-06-22 13:00:00
Jquery实现div模拟Select控件
2008-12-01 15:47:00
Python3.2中的字符串函数学习总结
2021-09-30 04:35:24
SQL对时间处理的语句小结
2011-12-01 07:53:04
Python中使用copy模块实现列表(list)拷贝
2022-05-13 02:46:48
Python游戏推箱子的实现
2023-09-23 05:31:27
![](https://img.aspxhome.com/file/2023/9/70759_0s.jpg)
javascript中css的float特殊写法
2007-12-24 20:24:00
phpMyAdmin下载、安装和使用入门
2007-06-15 11:00:00
![](https://img.aspxhome.com/file/uploadpic/20076/15/2007615151216820.gif)
无忧贴子管理器(ListView组件)
2009-01-02 17:56:00
如何获取浏览器的更多信息?
2009-11-23 20:48:00
CSS控制字体效果的思考
2011-06-14 09:44:02
![](https://img.aspxhome.com/file/UploadPic/20072/20072311315168s.gif)
python 实现的截屏工具
2023-05-15 00:20:39
![](https://img.aspxhome.com/file/2023/5/86215_0s.png)
Ubuntu下Python+Flask分分钟搭建自己的服务器教程
2023-11-12 04:37:43
![](https://img.aspxhome.com/file/2023/2/63182_0s.jpg)
z-index在IE中的迷惑
2007-05-11 16:50:00
教你用Python读取CSV文件的5种方式
2022-12-11 15:32:51
![](https://img.aspxhome.com/file/2023/1/75331_0s.png)