Python multiprocessing.Process.is_alive() 返回 True 虽然进程已经完成,为什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19353677/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:32:57  来源:igfitidea点击:

multiprocessing.Process.is_alive() returns True although process has finished, why?

pythonmultiprocessing

提问by zhanxw

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

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

Code:

代码:

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)

Output:

输出:

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

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

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

采纳答案by falsetru

You should use Process.joininstead of os.wait4.

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

http://asciinema.org/a/5901

http://asciinema.org/a/5901



Replace following line:

替换以下行:

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

with:

和:

proc.join()