python - 如何等待父进程退出子进程?

标签 python linux fork

我想 fork 一个进程,等待父进程退出,然后再对子进程做一些事情。

最佳答案

天真的方法是这样一个繁忙的循环:

# BAD WAY!
pid = os.fork()
if pid == 0:
    while True:
        if os.path.isdir("/proc/%s" % pid):
            break
        time.sleep(0.1)
    # Parent is dead there.

但这很容易受到 PID 重用问题的影响。如果在父进程退出并获取其 PID 后立即创建另一个进程,则子进程将永远不会退出。

另一种方法是对特定文件使用 flock()。但这是行不通的,因为 child 与 parent 共享相同的锁。

一个万无一失的方法是使用一个特殊的技巧:在父级中创建一个管道,在子级中,您只需等待直到获得 EOF。

# Good way
read_fd, write_fd = os.pipe()

pid = os.fork()
if pid > 0:
    # Close the read pipe, so that only the child is the reader.
    os.close(read_fd)

    # It is important to voluntarily leak write_fd there,
    # so that the kernel will close it for the parent process
    # when it will exit, triggering our trick.

elif pid == 0:
    # Daemon ourselves first.
    os.setsid()
    for fd in {0, 1, 2}:
        os.close(fd)

    # Close the write pipe so that the parent is the only writer.
    # This will make sure we then get an EOF when the only writer exits.
    os.close(write_fd)

    # Now, we're waiting on the read pipe for an EOF.
    # PS: the assert is not necessary in production...
    assert os.read(read_fd, 1) == ""
    os.close(read_fd)

    # At this point, the parent is dead.

关于python - 如何等待父进程退出子进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48703231/

相关文章:

python - 如何写入在 python 中使用 fork() 获得的子进程标准输入?

python - 从 csv 文件中删除货币值(value)列中的引号?

python - 删除 Conda 环境

linux -/proc/meminfo 中的条目

c - 无法使用线程编码来替代 fork()

python - 我有几个 Linux 命令,我想在 Windows 机器上运行。如何在 Windows 上从 Python 运行 Linux 命令

linux - 允许对/var/www/html 的完全权限

linux - 我的笔记本电脑有很多分区,我不知道在哪里安装 Linux

c - 下面的代码创建了多少个子进程

python - 如何检测系统是否支持 python 中的进程 fork ?