如何分别从子进程派生子进程

时间:2016-12-17 12:00:46

标签: python linux process multiprocessing fork

我有来自父进程的fork子进程的代码,我知道:

os.fork()创建上一个Python会话的副本并并行打开它,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

2 个答案:

答案 0 :(得分:0)

如果再次从孩子那里调用fork(),则第一级孩子的返回值将为0,而第二级孩子(孩子的孩子)的返回值将为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)

答案 1 :(得分:0)

感谢AsTeR和chrk。在我阅读了答案和一些游戏后,我最终得到了这个。我使用了os.wait()

import os

reply = int(input("Enter no of proc:   "))
pid = 0

for i in range(reply):

    if pid == 0:
        pid = os.fork()

if pid != 0:
    os.wait()
    print("PID = {}, PPID = {}".format(os.getpid(), os.getppid()))

num_process = 3的结果是:

Enter no of proc:   3
PID = 49312, PPID = 49311
PID = 49311, PPID = 49309
PID = 49309, PPID = 20928