Python Shared Memory: Resource Trackers, Process Lifetime, and Premature Cleanup
Learn how Python shared-memory resource tracking can prematurely unlink POSIX shared memory and how to manage ownership across independent processes.
A Python consumer attaches to shared memory, reads its data, closes its handle, and exits. Everything appears normal. Minutes later, a replacement consumer tries to attach to the same name and receives FileNotFoundError.
The producer is still running. Its existing mapping still contains readable data. No application code explicitly deleted the block.
This failure exposes a distinction that shared-memory examples often leave unexplained: accessing a resource and owning its lifetime are separate responsibilities. Python’s resource tracker can assign cleanup responsibility to a process that the application considers only a borrower.
For independently launched processes on POSIX systems, that mismatch can make a healthy worker’s exit break future workers.
Reproduce the Missing Name
Use separate terminal sessions on Linux with Python 3.13 or later. The following producer creates a block and remains alive while other programs attach:
# producer.py
from multiprocessing import shared_memory
shm = shared_memory.SharedMemory(create=True, size=64)
shm.buf[:5] = b"HELLO"
try:
print("name:", shm.name, flush=True)
input("Run the consumer, then press Enter...")
print("existing mapping:", bytes(shm.buf[:5]))
input("Run the probe, then press Enter...")
finally:
shm.close()
try:
shm.unlink()
except FileNotFoundError:
print("The shared-memory name was already removed.")
The final cleanup handles a missing name so the experiment can terminate cleanly. It does not prevent the premature removal being investigated.
Next, run this consumer from another terminal, passing the printed name:
# consumer.py
import sys
from multiprocessing import shared_memory
shm = shared_memory.SharedMemory(name=sys.argv[1])
try:
print("consumer:", bytes(shm.buf[:5]))
finally:
shm.close()
The consumer reads successfully and exits. Its resource tracker may then report a leaked shared-memory object during shutdown.
After that cleanup has completed, test a new attachment:
# probe.py
import sys
from multiprocessing import shared_memory
try:
shm = shared_memory.SharedMemory(
name=sys.argv[1],
track=False,
)
except FileNotFoundError:
print("The shared-memory name is unavailable.")
else:
try:
print("probe:", bytes(shm.buf[:5]))
finally:
shm.close()
The probe disables tracking so the diagnostic itself does not introduce another cleanup authority. Tracker shutdown is asynchronous, so a probe launched immediately after the consumer may race with cleanup.
The revealing outcome is that the probe fails while the producer still prints b'HELLO'.
Closing Access Does Not Relinquish Tracking
The consumer appears to follow a reasonable contract: attach, use, close. The problem is that closing its local access does not tell the resource tracker that somebody else owns the block.
With tracking enabled, attaching to an existing block can register its name for cleanup. When an independent consumer exits, its tracker can interpret the remaining registration as a leaked resource and unlink it.
This behavior is documented in CPython issue #104291, which describes an attaching process calling close() and still causing the underlying shared-memory name to be removed at shutdown.
The tracker is performing leak recovery. The application has simply failed to communicate the ownership arrangement it intended.
That makes this different from forgetting a finally block. More careful local closing does not resolve disagreement over who may perform global cleanup.
Process Topology Changes the Outcome
Python processes created through multiprocessing from a common ancestor share a resource tracker. Independently launched Python programs can have separate trackers for the same named block.
Python’s documentation explicitly warns that standalone processes using tracking can cause the first terminating process’s tracker to delete the shared memory. It recommends track=False when another process already handles bookkeeping. The public parameter was added in Python 3.13. See the SharedMemory documentation.
This explains why a prototype can work with a local process pool and fail after deployment introduces separately supervised workers.
The data-sharing code may be unchanged. The lifetime arrangement has changed substantially.
When reviewing a design, draw the actual process relationships: who launches each interpreter, which components restart independently, and which process must remain alive for replacement workers to attach. Those relationships determine whether automatic cleanup matches the application’s expectations.
Why Existing Workers Remain Healthy
POSIX separates a shared-memory object’s name from references already held by processes.
Unlinking removes the name used for new attachments. Existing references can keep the underlying object alive until those references are released. This behavior is specified in the POSIX shm_unlink() documentation.
An existing worker therefore has something a replacement worker lacks: an established mapping.
This produces a misleading operational pattern. Long-running workers continue processing, so ordinary health checks pass. Newly started workers fail because they must resolve the missing name.
Avoid automatically recreating the same name as a recovery shortcut. On POSIX, that can create a different object while surviving workers retain mappings to the old one. Processes may then believe they share data while actually accessing separate blocks.
Recovery should coordinate a new resource generation and tell every participant which generation to use.
Give Borrowers a Different Contract
For an independent consumer whose lifetime does not control the block, make the attachment policy explicit:
shm = shared_memory.SharedMemory(
name=shared_name,
create=False,
track=False,
)
try:
process_data(shm.buf)
finally:
shm.close()
Here, process_data represents application logic. Any retained buffer views must be released before closing the mapping.
Apply the same policy to short-lived utilities, probes, maintenance scripts, and replacement workers. One overlooked standalone client using default tracking can reintroduce premature cleanup.
Keep this decision in a shared attachment helper rather than repeating constructor arguments throughout the codebase. That makes ownership visible during review and reduces configuration drift.
Disabling borrower tracking still leaves a necessary question: which component performs final cleanup?
Match Ownership to the Resource’s Lifetime
A long-lived producer can own a block when its shutdown genuinely marks the end of that block’s usefulness. It creates the resource, allows borrowers to attach, stops new work, waits for consumers to finish, and performs final cleanup.
That model fails when producers restart routinely while consumers are expected to continue.
In that case, place ownership in a more stable supervisor or dedicated manager. Prefer having that owner create the block directly. A temporary creator with tracking enabled can otherwise retain an unintended cleanup path.
SharedMemoryManager provides a dedicated lifecycle boundary and unlinks the blocks it manages during shutdown. Its scope must therefore cover all intended users. See the manager documentation.
An ownership protocol should also cover crashes. If the owner dies, decide whether the application rebuilds the resource or attempts controlled recovery. Disabling tracking everywhere without a recovery and cleanup plan simply exchanges premature deletion for leaks.
Test Lifecycle Events, Not Just Data Transfer
A successful read proves that attachment works at one moment. It says little about whether the resource survives routine process changes.
Include these scenarios in integration testing:
- A standalone borrower exits normally, followed by a new attachment.
- A borrower crashes while the owner remains alive.
- The producer restarts while consumers remain active.
- The designated owner shuts down and cleanup completes.
- A replacement resource is created without mixing generations.
Record resource names, owner identities, generations, and attachment failures. On Linux, a disappearing entry under /dev/shm, combined with readable existing mappings, is a useful diagnostic clue.
Platform assumptions also matter. Python ignores track on Windows, where shared-memory lifetime follows open handles. Older Python versions lack the public argument. Validate the deployment’s actual interpreter versions and operating systems rather than extrapolating from one development machine.
Shared memory removes serialization from the data path, but it does not remove coordination from the architecture. Reliable operation depends on making resource ownership as explicit as the buffer layout: borrowers release their access, and a designated owner decides when the shared resource is finished.
Opinions expressed by DZone contributors are their own.