python - fork python,不存在的 child

标签 python fork zombie-process

我在 Python 子进程方面遇到了一些麻烦,所以我写了一个非常简单的脚本:

import os
import sys
import time

pid = os.fork()
if pid:
    #parent
    time.sleep(30)
else:
    #child
    #os._exit(0)
    sys.exit()

当父进程休眠时我启动

ps fax | grep py[t]hon

然后我读了这个输出

2577 ?        S      0:00 python /home/pi/python/GPIO/GPIODaemon.py restart
2583 ?        Z      0:00  \_ [python] <defunct>

使用 sys.exit()os._exit(0) 总是有僵尸进程,我无法理解为什么。

处理我更复杂的代码时,我认为子进程锁定了一些资源,但在这个简化的代码中,子进程根本没有文件/套接字/数据库连接!为什么子进程僵尸化?

最佳答案

要清除 Unix 中的子进程,您需要等待子进程,检查 http://docs.python.org/2/library/os.html#os.wait 处的 os.wait()、os.waitpid()、os.wait3() 或 os.wait4() 之一。

至于为什么会这样,这是Unix的设计决定。子进程将其返回值保持在其进程状态,如果它消失,您将没有返回值。 os.wait() 也将返回值返回给你,然后释放子进程并释放所有相关资源。

关于python - fork python,不存在的 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18090230/

相关文章:

c - fork() 代码的可能输出

c - 在 Linux/Unix 中用 C 语言管理进程 fork

c - 你如何使用 wait() 杀死僵尸进程

linux - 关于僵尸进程和线程的问题

Python-诅咒 : how to use the inch method to get the attribute of a character

python - 加速 Python

python re.sub 组 : number after\number

python - 在 Flask 中使用隐藏字段_method 更改请求方法

windows - 为什么 Windows 上的 Perl IO::Socket 在 64 个连接后会提示 "Resource Not Available"?

python - 在写入其标准输入后后台进程