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

时间:2013-10-14 04:48:29

标签: python multiprocessing

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

代码:

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。怎么会发生这种情况?

1 个答案:

答案 0 :(得分:11)

您应该使用Process.join代替os.wait4

http://asciinema.org/a/5901


替换以下行:

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

使用:

proc.join()