尽管处理完成,multiprocessing.Process.is_alive()返回True,为什么? [英] multiprocessing.Process.is_alive() returns True although process has finished, why?

查看:819
本文介绍了尽管处理完成,multiprocessing.Process.is_alive()返回True,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用multiprocess.Process创建一个子进程,然后调用os.wait4直到子存在.当实际的子进程完成时,multiprocess.Process.is_alive()仍返回True.这是矛盾的.为什么?

I use multiprocess.Process to create a child process and then call os.wait4 until child exists. When the actual child process finishes, multiprocess.Process.is_alive() still returns True. That's contradicting. Why?

代码:

from multiprocessing import Process
import os, sys

proc = Process(target=os.system, args= ("sleep 2", ))
proc.start()

print "is_alive()", proc.is_alive()
ret = os.wait4(proc.pid, 0)
procPid, procStatus, procRes = ret
print "wait4 = ", ret

## Puzzled!
print "----Puzzled below----"
print "is_alive()", proc.is_alive()
if os.WIFEXITED(procStatus):
    print "exit with status", os.WEXITSTATUS(procStatus)
print "is_alive()", proc.is_alive()
sys.exit(1)

输出:

is_alive() True
wait4 =  (11137, 0, resource.struct_rusage(ru_utime=0.0028959999999999997, ru_stime=0.003189, ru_maxrss=1363968, ru_ixrss=0, ru_idrss=0, ru_isrss=0, ru_minflt=818, ru_majflt=0, ru_nswap=0, ru_inblock=0, ru_oublock=0, ru_msgsnd=0, ru_msgrcv=0, ru_nsignals=0, ru_nvcsw=1, ru_nivcsw=9))
----Puzzled below----
is_alive() True
exit with status 0
is_alive() True

我的问题是关于最后三行输出.实际过程完成后,为什么is_alive()返回True.怎么会这样?

My question is about the last three output lines. Why is_alive() return True when the actual process is finished. How can that happen?

推荐答案

您应使用 Process.join 而不是os.wait4.

  • Process.is_alive通过multiprocessing.forking.Popen.poll内部调用waitpid.
  • 如果调用os.wait4,则waitpid会升高os.error,这会导致poll()返回None. ( http://hg.python.org/cpython/文件/c167ab1c49c9/Lib/multiprocessing/forking.py#l141 )
  • is_alive()使用该返回值来确定该进程是否仍在运行. ( http://hg.python.org/cpython/文件/c167ab1c49c9/Lib/multiprocessing/process.py#l159 )
    • =>返回True.
    • Process.is_alive calls waitpid internally through multiprocessing.forking.Popen.poll.
    • If you call os.wait4, waitpid raises os.error which cause the poll() to return None. (http://hg.python.org/cpython/file/c167ab1c49c9/Lib/multiprocessing/forking.py#l141)
    • is_alive() use that return value to determine whether the process is alive. (http://hg.python.org/cpython/file/c167ab1c49c9/Lib/multiprocessing/process.py#l159)
      • => return True.

      http://asciinema.org/a/5901

      替换以下行:

      ret = os.wait4(proc.pid, 0)
      

      具有:

      proc.join()
      

      这篇关于尽管处理完成,multiprocessing.Process.is_alive()返回True,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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