Python 3:子进程导致僵尸
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python 3:子进程导致僵尸相关的知识,希望对你有一定的参考价值。
继the popular answers to this question和here指令后,我在python 3中创建了以下代码:
p1 = subprocess.Popen(["ps", "-e", "-o", "pcpu,args"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p2 = subprocess.Popen(["cut", "-c", "-132"], stdin=p1.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p3 = subprocess.Popen(["awk", "NR>2"], stdin=p2.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p4 = subprocess.Popen(["sort", "-nr"], stdin=p3.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p5 = subprocess.Popen(["head", "-10"], stdin=p4.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
ps,err = p5.communicate()
psout = str(ps, 'utf-8')
这个代码在循环中每分钟左右调用一次。与我所相信的相反,这仍然会造成僵尸。我究竟做错了什么?
编辑:运行代码时的僵尸:
$ ps -eo pid,ppid,state,cmd | awk '$3 == "Z"'
14441 11232 Z [ps] <defunct>
14442 11232 Z [cut] <defunct>
14445 11232 Z [sort] <defunct>
答案
你需要使用communicate()
来处理所有子进程,以摆脱'defunct'进程。
以上是关于Python 3:子进程导致僵尸的主要内容,如果未能解决你的问题,请参考以下文章