本文介绍了分叉的python,已失效的子级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have some troubles with Python child processes so I wrote a very simple script:

import os
import sys
import time

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

当父进程处于休眠状态时,我启动

While parent process is sleeping I launch

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)总是存在一个僵尸进程,而我无法理解为什么.

Using sys.exit()oros._exit(0) there is always a Zombie process and I'm unable to understand why.

在处理更复杂的代码时,我以为子进程一直处于锁定状态,但是在这个简化的代码上,子进程根本没有文件/套接字/数据库连接!为什么子进程被僵死了?

Working on my more complex code I was thinking that there was some resources that child processes were keeping locked, but on this simplified code child has no file/socket/db connection at all! Why is child process zombiefied?

推荐答案

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

To clear the child process in Unix you need to wait on the child, check one of the os.wait(), os.waitpid(), os.wait3() or os.wait4() at http://docs.python.org/2/library/os.html#os.wait

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

As to why this is so, this is a design decision of Unix. The child process keeps its return value in its process state, if it was to disappear you'll have no return value. The os.wait() also returns to you the return value and then the child process is released and all associated resources are released.

这篇关于分叉的python,已失效的子级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 05:33