Python fork 进程不会死

Jay*_*Lev 3 python

我见过几个这样的问题,但是在尝试了检查孩子是否还活着并退出孩子进程的各种变体之后,我简化了问题,但仍然无法解决。

使用 sys.exit(0) 退出分叉进程是否有误?有没有其他方法可以杀死它。问题是,我不能让父进程终止进程,因为它不知道它们何时完成工作。

起初我以为是因为在退出之前执行了一个系统命令(Python 运行系统命令然后退出...不会退出),但我什至在简化版本中删除了它,因为给定的解决方案也不起作用.

下面是一个例子:

import sys
import os
import time

children = []

for i in range(0,3):    
    pid = os.fork()

    if pid == -1:
        continue
    elif pid == 0:
        # Do work...
        print 'Child %d spawned' % os.getpid()
        sys.exit(0)     
    else:
        children.append(pid)

time.sleep(5)
for pid in children:
    proc_path = '/proc/%d' % pid
    if not os.path.exists(proc_path):
        print 'Child %d is dead' % pid
    else:
        print 'Child %d is alive' % pid
Run Code Online (Sandbox Code Playgroud)

这打印:

Child 27636 spawned
Child 27637 spawned
Child 27638 spawned
Child 27636 is alive
Child 27637 is alive
Child 27638 is alive
Run Code Online (Sandbox Code Playgroud)

但是子进程应该是死的。

在这种情况下,是什么导致这些进程变成僵尸进程?

And*_*ath 5

你必须wait()为子进程。

请添加以下几行以纠正问题:

import sys
import os
import time

children = []

for i in range(0,3):    
    pid = os.fork()

    if pid == -1:
        continue
    elif pid == 0:
        # Do work...
        print 'Child %d spawned' % os.getpid()
        sys.exit(0)     
    else:
        children.append(pid)

time.sleep(5)

# ADD NEXT TWO LINES:
for pid in children:
    os.waitpid(pid, 0)

for pid in children:
    proc_path = '/proc/%d' % pid
    if not os.path.exists(proc_path):
        print 'Child %d is dead' % pid
    else:
        print 'Child %d is alive' % pid
Run Code Online (Sandbox Code Playgroud)

父母必须wait()为孩子。详情请参阅man 2 wait

在python中,您可以使用subprocess模块处理这些事情。