python / python/cpython

multiprocessing SharedMemory.__del__ can fail, leak file descriptor

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

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

stdlib topic-multiprocessing type-bug
主要言語
Python
スター
77.2k
フォーク
35.9k
PR マージ指標
PR 指標を取得中

説明

Bug report

Bug description:

When a SharedMemory object goes out of scope, its __del__ method calls self.close() to clean it up. This can break if there is still a buffer exported from its mmap instance. It tries to close the mmap before the fd, so in this case it will leave the file descriptor open:

>>> from multiprocessing.shared_memory import SharedMemory
>>> import os
>>> def shview(size=4096):
...     shmem = SharedMemory(create=True, size=size)
...     print("fd is:", shmem._fd)
...     return shmem.buf.cast('i')
...     
>>> mv = shview()
fd is: 5
Exception ignored while calling deallocator <function SharedMemory.__del__ at 0x7f686264d640>:
Traceback (most recent call last):
  File "/usr/lib64/python3.14/multiprocessing/shared_memory.py", line 189, in __del__
    self.close()
  File "/usr/lib64/python3.14/multiprocessing/shared_memory.py", line 232, in close
    self._mmap.close()
BufferError: cannot close exported pointers exist
>>> os.fstat(5).st_size  # fd still open
4096

I think a better option for __del__ would be to close the fd and leave the mmap & buf objects alone, to be cleaned up as normal by reference counting or GC:

>>> class SharedMemoryFix(SharedMemory):
...     def __del__(self):
...         if self._fd >= 0:
...             os.close(self._fd)
...             self._fd = -1
...             
>>> def shview(size=4096):
...     shmem = SharedMemoryFix(create=True, size=size)
...     print("fd is:", shmem._fd)
...     return shmem.buf.cast('i')
...     
>>> mv = shview()
fd is: 7
>>> os.fstat(7)
Traceback (most recent call last):
  File "<python-input-8>", line 1, in <module>
    os.fstat(7)
    ~~~~~~~~^^^
OSError: [Errno 9] Bad file descriptor

(I'm thinking about the POSIX side here. IDK if the behaviour on Windows needs to be different, though I guess it can rely on the mmap's dealloc too)

CPython versions tested on:

3.14

Operating systems tested on:

Linux

Linked PRs
  • gh-155007
  • gh-155070

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

Lib/multiprocessing/shared_memory.py の SharedMemory.del と close() から始め、issue にある Linux での再現を使って、エクスポートされたバッファーの失敗とリークしたファイルディスクリプターを確認します。開始する前に、リンクされている PR gh-155007 と gh-155070 を確認してください。完了とは、関連する mmap とバッファーの動作を維持しながら、デストラクターがディスクリプターを開いたままにしなくなることです。

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

評価

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

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

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