linux python subprocess.popen 引起的僵尸进程 defunct 解决方法

使用 popen 函数的时候,如果不注意的话,可能会引起僵尸进程 defunct 的存在,虽然该进程不占用内存和 cpu,但是会在进程任务管理树上占用一个宝贵的节点。这样就造成了进程名额的资源浪费,所以一定得处理僵尸进程!

下面以 python 为例来说明:

python 脚本如下(zombie.py):

#!/usr/bin/env python
#-*-encoding:UTF-8-*-
 
import os
import time
import subprocess
 
 
if __name__ == '__main__':
    p = subprocess.Popen('ls',shell=True,close_fds=True,bufsize=-1,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
    file =  p.stdout.readlines()
 
    for i in range(0,len(file)):
        print file[i]
    #end for
 
 
    while True:
        time.sleep(1)
    #end while
#end if

运行结果如下:

我们用 top 命令查看此时有没有僵尸进程,结果如下:

用 ps axf 命令查看具体的僵尸进程,结果如下:

查看相关资料后发现,在使用 popen 函数后,需要调用 wait 函数(等待子进程中断或结束),否则就会产生僵尸进程,于是上面的代码做了简单修改

#!/usr/bin/env python
#-*-encoding:UTF-8-*-
 
import os
import time
import subprocess
 
 
if __name__ == '__main__':
    p = subprocess.Popen('ls',stderr=subprocess.STDOUT)
    file =  p.stdout.readlines()
    p.wait()     # 添加 wait 函数
 
    for i in range(0,len(file)):
        print file[i]
    #end for
 
 
    while True:
        time.sleep(1)
    #end while
#end if

执行结果不变,但是使用 top 名令查看僵尸进程的个数,结果如下:

使用 ps axf 命令查看结果如下:

并无僵尸进程。

 

wait() 函数功能

 wait() 会暂时停止目前进程的执行,直到有信号来到或子进程结束。如果在调用 wait() 时子进程已经结束,则 wait() 会立即返回子进程结束状态值。子进程的结束状态值会由参数 status 返回,而子进程的进程识别码也会一快返回。

 

 

相关文章

在Linux系统中,设置ARP防火墙可以通过多种方法实现,包括使...
在Linux环境下,使用Jack2进行编译时,可以采取以下策略来提...
`getid`命令在Linux系统中用于获取当前进程的有效用户ID(EU...
在Linux环境下,codesign工具用于对代码进行签名,以确保其完...
Linux中的`tr`命令,其英文全称是“transform”,即转换的意...
Linux中的ARP防火墙是一种用于防止ARP欺骗攻击的安全措施,它...