📧 Interprocess Communication: Shared Memory
🎯 Learning Objective
- Understand interprocess communication (IPC) mechanisms using shared memory.
- Identify the role of the operating system in managing network connections.
📜 Statement
In this exercise, you will create two Python modules for
🔧 Step 1 – Writer Module
Create a file called writer.py and copy the following code:
# writer.py
from multiprocessing import shared_memory
import time
# Create a new shared memory block
shm = shared_memory.SharedMemory(name="demo_shm", create=True, size=1024)
# Write some bytes
shm.buf[:10] = b"Hello IPC!"
print("Writer: wrote to shared memory.")
time.sleep(60) # Give reader time to read it
# Clean up
shm.close()
shm.unlink() # Only the creating process should unlink
💬 Step 2 – Reader Module
Create a file reader.py:
# reader.py
from multiprocessing import shared_memory
# Connect to existing shared memory
existing_shm = shared_memory.SharedMemory(name="demo_shm")
# Read from it
data = bytes(existing_shm.buf[:11])
print("Reader: read from shared memory:", data.decode())
existing_shm.close()
🔁 Step 3 – Test
To test, open two terminals. In the first terminal, run the writer.py module:
python writer.py
In the second terminal, run the reader.py module:
python reader.py
📝 Step 4 – The Operating System
- What is the role of the operating system in managing shared memory?
- Which processes can access the shared memory named
demo_shm? - What happens if the
writer.pyprocess finishes beforereader.pycan read the data? - Does the operating system manage synchronization between processes accessing shared memory?