如何使用子进程模块杀死(或避免)僵尸进程 [英] how to kill (or avoid) zombie processes with subprocess module

查看:123
本文介绍了如何使用子进程模块杀死(或避免)僵尸进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用 subprocess 模块从另一个 python 脚本中启动 python 脚本时,子进程完成"时会创建一个僵尸进程.除非我杀死我的父 python 进程,否则我无法杀死这个子进程.

When I kick off a python script from within another python script using the subprocess module, a zombie process is created when the subprocess "completes". I am unable to kill this subprocess unless I kill my parent python process.

有没有办法在不杀死父进程的情况下杀死子进程?我知道我可以通过使用 wait() 来做到这一点,但我需要使用 no_wait() 运行我的脚本.

Is there a way to kill the subprocess without killing the parent? I know I can do this by using wait(), but I need to run my script with no_wait().

推荐答案

僵尸进程不是真正的进程;它只是进程表中的剩余条目,直到父进程请求子进程的返回代码.实际进程已经结束,除了上述进程表条目外,不需要其他资源.

A zombie process is not a real process; it's just a remaining entry in the process table until the parent process requests the child's return code. The actual process has ended and requires no other resources but said process table entry.

我们可能需要有关您运行的流程的更多信息才能真正提供更多帮助.

We probably need more information about the processes you run in order to actually help more.

但是,如果您的 Python 程序知道子进程何时结束(例如到达子标准输出数据的末尾),那么您可以安全地调用 process.wait():

However, in the case that your Python program knows when the child processes have ended (e.g. by reaching the end of the child stdout data), then you can safely call process.wait():

import subprocess

process= subprocess.Popen( ('ls', '-l', '/tmp'), stdout=subprocess.PIPE)

for line in process.stdout:
        pass

subprocess.call( ('ps', '-l') )
process.wait()
print "after wait"
subprocess.call( ('ps', '-l') )

示例输出:

$ python so2760652.py
F S   UID   PID  PPID  C PRI  NI ADDR SZ WCHAN  TTY          TIME CMD
0 S   501 21328 21326  0  80   0 -  1574 wait   pts/2    00:00:00 bash
0 S   501 21516 21328  0  80   0 -  1434 wait   pts/2    00:00:00 python
0 Z   501 21517 21516  0  80   0 -     0 exit   pts/2    00:00:00 ls <defunct>
0 R   501 21518 21516  0  80   0 -   608 -      pts/2    00:00:00 ps
after wait
F S   UID   PID  PPID  C PRI  NI ADDR SZ WCHAN  TTY          TIME CMD
0 S   501 21328 21326  0  80   0 -  1574 wait   pts/2    00:00:00 bash
0 S   501 21516 21328  0  80   0 -  1467 wait   pts/2    00:00:00 python
0 R   501 21519 21516  0  80   0 -   608 -      pts/2    00:00:00 ps

否则,您可以将所有子项保存在一个列表中,然后不时地.poll 获取它们的返回代码.每次迭代后,请记住从列表中删除返回代码不同于 None 的子项(即完成的子项).

Otherwise, you can keep all the children in a list, and now and then .poll for their return codes. After every iteration, remember to remove from the list the children with return codes different than None (i.e. the finished ones).

这篇关于如何使用子进程模块杀死(或避免)僵尸进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆