python - 如何分别从一个子进程fork一个子进程

标签 python linux process multiprocessing fork

我有这段代码用于从父进程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/

相关文章:

python - 如何将一个 python 字典附加到另一个,同时保留它们的键值?

python - 将数组作为命令行参数传递给 python 脚本

python - 如何使用目录 api 和 python 将成员添加到组中?

linux - 我可以防止 Linux 用户空间 pthread 在关键代码中让步吗?

linux - 如何在shell脚本中读取文件

python - pyglet/avbin 错过了视频的开头和结尾

linux - 如何检查 sed 命令是否替换了一些字符串?

linux - 将参数传递并解析到正在运行/在线的 systemd 守护进程

apache - 许多相同的 Apache Tomcat 子级在启动时自动生成

java - 如何使用进程 ID 获取有关 linux 进程的更多详细信息?