我正在计划一个 Python 脚本,它将使用 os.fork()
创建一堆子进程来执行一些计算。父进程将阻塞,直到子进程终止。
不同之处在于,我需要能够使用 python
从 Unix shell 和使用 %run
从 ipython
运行脚本.
子进程应该以何种方式终止以避免返回到 ipython
命令提示符?根据我的经验,sys.exit()
不行。
最佳答案
以下似乎有效:
import os, sys
child_pid = os.fork()
if child_pid == 0:
print 'in child'
os._exit(os.EX_OK)
print 'hm... wasn''t supposed to get here'
else:
print 'in parent'
诀窍是使用 os._exit()
而不是 sys.exit()
.该文档包含以下段落:
Note The standard way to exit is
sys.exit(n)
._exit()
should normally only be used in the child process after a fork().
关于python - ipython 和 fork(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6049741/