You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python multiprocessing.Connection未按规范抛出EOFError问题问询

关于multiprocessing.Pipe的recv()未抛出EOFError的问题

根据Python规范,multiprocessing.Pipe()返回的Connection对象的recv()方法,在管道为空且另一端关闭时应抛出EOFError。

我编写了以下测试代码,预期父进程关闭管道后子进程立即退出——不会出现大量"still alive!"输出,且能看到"no val (got EOFError)"的输出:

import multiprocessing as mp
import sys
import time
from multiprocessing.connection import Connection


def foo(conn: Connection):
    while True:
        try:
            val = conn.recv()
        except EOFError:
            print("no val (got EOFError)")
            return
        print(f"got val {val}")

if __name__ == "__main__":
    print(f"Version: {sys.version}")
    conn_r, conn_w = mp.Pipe(duplex=False)
    proc=mp.Process(target=foo, args=(conn_r,))
    proc.start()
    conn_r.close()
    for i in range(10):
        time.sleep(0.1)
        conn_w.send(i)
    conn_w.close()
    while True:
        if not proc.is_alive():
            break
        print("still alive!")
        proc.join(timeout=0.1)

但实际运行结果是子进程永不退出,也未捕获到EOFError异常,输出如下:

$ python3 test_pipe.py
Version: 3.9.2 (default, Feb 28 2021, 17:03:44)
[GCC 10.2.1 20210110]
got val 0
got val 1
got val 2
got val 3
got val 4
got val 5
got val 6
got val 7
got val 8
still alive!
got val 9
still alive!
still alive!
still alive!
still alive!
still alive!
still alive!
still alive!
still alive!
still alive!
still alive!
still alive!
still alive!
still alive!
still alive!
still alive!
still alive!
still alive!
...

该问题在Python 3.10版本中同样存在。请问我是否遗漏了什么?在你的电脑和Python版本上运行情况如何?这是否属于Python实现的bug?

内容的提问来源于stack exchange,提问作者milaniez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 10:35:03