17

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怎么会这样?

4

1 回答 1

18

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

http://asciinema.org/a/5901


替换以下行:

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

和:

proc.join()
于 2013-10-14T04:56:57.260 回答