python / python/cpython

multiprocessing.Process cannot be closed if the process is reaped elsewhere

未关闭
#94,661 1 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

topic-multiprocessing type-bug
主要语言
Python
星标
77.2k
派生
36k
PR 合并指标
PR 指标待抓取

描述

Here's a small reproducer where I start a multiprocessing.Process - then reap it with os.waitpid(

import os
import multiprocessing
import socket
import sys


ctx = multiprocessing.get_context("spawn")

def target(sock):
    with sock:
        sock.send(b"\x00")
        sock.recv(1)


def main():
    a, b = socket.socketpair()
    with a, b:
        with b:
            proc = ctx.Process(target=target, args=(b, ))
            proc.start()
        assert a.recv(1) == b"\x00"
        a.send(b"\x00")
        os.waitpid(proc.pid, 0)
        if sys.version_info >= (3, 7):
            proc.close()
        elif proc.is_alive():
            raise RuntimeError("proc={proc} is still running".format(proc=proc))


if __name__ == "__main__":
    sys.exit(main())

which results in:

 Traceback (most recent call last):
  File "/home/graingert/projects/distributed/demo.py", line 31, in <module>
    sys.exit(main())
  File "/home/graingert/projects/distributed/demo.py", line 25, in main
    proc.close()
  File "/home/graingert/miniconda3/lib/python3.9/multiprocessing/process.py", line 181, in close
    raise ValueError("Cannot close a process while it is still running. "
ValueError: Cannot close a process while it is still running. You should first call join() or terminate().

One issue is the call to self._popen.poll() suppresses the OSError of a reaped process:
https://github.com/python/cpython/blob/b6558d768f19584ad724be23030603280f9e6361/Lib/multiprocessing/popen_fork.py#L26-L31

I think this can be fixed by checking the state of the multiprocessing.Process.sentinel instead of using os.waitpid

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

从 issue 中的 reproducer 开始,检查 Lib/multiprocessing/popen_fork.py,尤其是 _popen.poll() 的处理,以及 multiprocessing.Process.close()。调查一个被外部 reaped 的进程如何由其 sentinel 表示,并将其与基于 waitpid 的状态检测进行比较。当 reproducer 可以从外部 reaped 子进程,然后关闭 Process,而不会错误地触发表示进程仍在运行的 ValueError 时,即视为完成。

由索引模型根据 Issue 内容生成。

评估

技术栈
python
领域
operating-systems
Issue 类型
缺陷
难度
4/5
预计耗时
3-5 天
活跃度
停滞
描述清晰度
基本清楚
新手友好度
35/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。