我有这段代码用于从父进程fork
一个子进程,我知道:
os.fork()
创建先前 Python session 的副本并并行打开它,os.fork()
返回新进程的 ID。
我想分别从一个子进程派生一个子进程,但总是从父进程派生。如何做到这一点。
import os
def child():
print( 'this is child', os.getpgid())
os._exit()
def parent():
while True:
newpid = os.fork()
if newpid ==0:
child()
else:
pids = (os.getpid(), newpid)
print("parent: %d, child: %d\n", pids)
reply = input("q for quit / c for new fork\n")
if reply == 'c':
continue
else:
break
parent()
以上代码的输出:
parent: %d, child: %d
(1669, 3685)
q for quit / c for new fork
c
parent: %d, child: %d
(1669, 3686)
q for quit / c for new fork
c
parent: %d, child: %d
(1669, 3688)
q for quit / c for new fork
c
parent: %d, child: %d
(1669, 3689)
q for quit / c for new fork
q
最佳答案
如果您再次从 child 调用 fork(),则返回值对于第一级 child 将非 0,对于第二级 child ( child 的 child )将返回 0。
没有任何尝试:
def child():
print( 'this is child', os.getpid())
if os.fork() == 0:
print( 'this is a grand child', os.getpid())
os._exit(0)
输出:
('parent: %d, child: %d\n', (9663, 9664))
('this is child', 9664)
('this is a grand child', 9665)
关于python - 如何分别从一个子进程fork一个子进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41198362/