python / python/cpython

multiprocessing SharedMemory.__del__ can fail, leak file descriptor

未關閉
#155,003 1 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視

還沒有人認領這個 Issue。

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. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 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 摘要。