python / python/cpython

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

オープン
#94,661 コメント 1 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

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. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

Issue の reproducer から始めて、Lib/multiprocessing/popen_fork.py、特に _popen.poll() の処理を、multiprocessing.Process.close() と合わせて調査します。外部から reaped されたプロセスが sentinel によってどのように表現されるかを調べ、それを waitpid ベースの状態検出と比較します。reproducer で子プロセスを外部から reaping した後、誤ってまだ実行中であることを示す ValueError を発生させずに Process を close できれば完了です。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
python
領域
operating-systems
issue の種類
バグ
難易度
4/5
見積もり時間
3〜5日
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
35/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。