When allocating a SharedMemory block on linux, if there's insufficient shared memory on the system, creating the block works but accessing it triggers SIGBUS and the process crashes.
A file is created under /dev/shm and its size is reserved using ftruncate() in SharedMemory.__init__.
This in fact does not allocate the memory and causes SIGBUS to be sent when accessing the memory.
Instead, a call to fallocate() would throw an error when out of memory which can be caught and handled correctly by the user.
The existing code already captures OSError when calling ftruncate() but no error is thrown in this situation.
Note that this change should only run on linux - see explanation down in references.
So my suggested solution is:
class SharedMemory:
...
def __init__(self, name=None, create=False, size=0):
...
if _USE_POSIX:
... # set self._fd
try:
if create and size:
- os.ftruncate(self._fd, size)+ if _IS_LINUX:+ os.posix_fallocate(self._fd, 0, size)+ else:+ os.ftruncate(self._fd, size)
stats = os.fstat(self._fd)
size = stats.st_size
self._mmap = mmap.mmap(self._fd, size)
except OSError:
self.unlink()
raise
...
The change should only be for linux, as summarized in their commit:
Make this code #ifdef linux, because (a) there's not currently a
reason to think the same problem exists on other platforms, and (b)
applying posix_fallocate() to an FD created by shm_open() isn't very
portable anyway.
To people manually poking at internals such as os.posix_fallocate(shm._fd, 0, size) please do that conditionally on the existence of hasattr(shm, "_fd") so that it continues to function if we remove the private _fd attribute in the future... see #155007 for example.
Activity
hjhicks commented on Feb 19, 2025
I can confirm that this bug still exists; I ran into it today. Manually implementing the proposed solution does fix the issue.
vmarkovtsev commented on Apr 9, 2026
@MazinSharaf could you help us here, please? 🙏 This looks like a simple, low-risk fix.
gpshead commented on Jul 31, 2026
To people manually poking at internals such as os.posix_fallocate(shm._fd, 0, size) please do that conditionally on the existence of hasattr(shm, "_fd") so that it continues to function if we remove the private _fd attribute in the future... see #155007 for example.