Skip to content

Commit 6970bd3

Browse files
committed
gh-92408: cleanup during error handling for POSIX shared memory
`multiprocessing.shared_memory.SharedMemory` currently tries to unlink a POSIX shared memory object if it fails to `mmap` it after opening/creating it. However, since it only catches `OSError`, it fails to do so when opening an existing zero-length shared memory object, as `mmap.mmap` raises a `ValueError` when given a 0 size. Fix this by catching all exceptions with a bare `except`, so the cleanup is run for all errors.
1 parent 4e294f6 commit 6970bd3

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

Lib/multiprocessing/shared_memory.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ def __init__(self, name=None, create=False, size=0, *, track=True):
115115
stats = os.fstat(self._fd)
116116
size = stats.st_size
117117
self._mmap = mmap.mmap(self._fd, size)
118-
except OSError:
118+
except:
119119
self.unlink()
120120
raise
121121
if self._track:

Lib/test/_test_multiprocessing.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4851,6 +4851,23 @@ def test_shared_memory_tracking(self):
48514851
resource_tracker.unregister(mem._name, "shared_memory")
48524852
mem.close()
48534853

4854+
@unittest.skipIf(os.name != "posix", "posix-only test w/ empty file")
4855+
def test_cleanup_zero_length_shared_memory(self):
4856+
import _posixshmem
4857+
4858+
name = self._new_shm_name("test_init_cleanup")
4859+
mem = _posixshmem.shm_open(name, os.O_RDWR | os.O_CREAT | os.O_EXCL, 0o600)
4860+
os.close(mem)
4861+
4862+
# First time the mmap.mmap fails with a ValueError, as the shared
4863+
# memory is zero-length and hence the mmap fails...
4864+
with self.assertRaises(ValueError):
4865+
shared_memory.SharedMemory(name, create=False)
4866+
4867+
# ...however it should delete the shared memory as part of its cleanup
4868+
with self.assertRaises(FileNotFoundError):
4869+
_posixshmem.shm_open(name, os.O_RDWR)
4870+
48544871
#
48554872
# Test to verify that `Finalize` works.
48564873
#

0 commit comments

Comments
 (0)