os.waitpid文档https://docs.python.org/2.7/library/os.html#os.WNOHANG表示如果子进程尚未退出,则返回值为(0,0)
但是FreeBSD(FreeBSD 10.3-RELEASE-p7)有时为{{1} }}或(0,-512)
被返回。示例程序:
(0,-2048)
在osx(Python 2.7.11)和ubuntu(Python 2.7.6)上更正输出(类似/相同)
#!/usr/bin/env python
import os
import sys
import time
def show_waitpid_results(results):
print("results: %s" % (str(results)))
print("core: %r continued: %r stopped: %r signaled: %r exited %r" %
(
os.WCOREDUMP(results[1]),
os.WIFCONTINUED(results[1]),
os.WIFSTOPPED(results[1]),
os.WIFSIGNALED(results[1]),
os.WIFEXITED(results[1]))
)
if os.WIFEXITED(results[1]):
print("exit code: %r" % (os.WEXITSTATUS(results[1])))
if __name__ == '__main__':
try:
pid = os.fork()
if pid:
print("in parent. child pid: %r" % (pid))
while True:
waitpid_result = os.waitpid(pid, os.WNOHANG)
show_waitpid_results(waitpid_result)
if waitpid_result == (0,0) or waitpid_result == (0,-512):
time.sleep(.1)
pass
else:
break
print("parent exiting")
else:
# child
time.sleep(.5)
print("child exiting with exit code 10");
sys.exit(10)
except Exception:
e = sys.exc_info()[1]
print("error: %s"%(e))
sys.exit(20)
不正确? FreeBSD上的行为(Python 2.7.12):
in parent. child pid: 3196
results: (0, 0)
core: False continued: False stopped: False signaled: False exited True
exit code: 0
results: (0, 0)
core: False continued: False stopped: False signaled: False exited True
exit code: 0
results: (0, 0)
core: False continued: False stopped: False signaled: False exited True
exit code: 0
results: (0, 0)
core: False continued: False stopped: False signaled: False exited True
exit code: 0
results: (0, 0)
core: False continued: False stopped: False signaled: False exited True
exit code: 0
child exiting with exit code 10
results: (0, 0)
core: False continued: False stopped: False signaled: False exited True
exit code: 0
results: (3196, 2560)
core: False continued: False stopped: False signaled: False exited True
exit code: 10
parent exiting
我在FreeBSD下也见过-2048 vs. -512。
当使用in parent. child pid: 5054
results: (0, -512)
core: False continued: False stopped: False signaled: False exited True
exit code: -2
results: (0, -512)
core: False continued: False stopped: False signaled: False exited True
exit code: -2
results: (0, -512)
core: False continued: False stopped: False signaled: False exited True
exit code: -2
results: (0, -512)
core: False continued: False stopped: False signaled: False exited True
exit code: -2
results: (0, -512)
core: False continued: False stopped: False signaled: False exited True
exit code: -2
child exiting with exit code 10
results: (5054, 2560)
core: False continued: False stopped: False signaled: False exited True
exit code: 10
parent exiting
时,可能在FreeBSD上没有正确初始化状态值(返回元组中的第二个元素)?我可以不依赖waitpid返回os.WNOHANG
吗?