POSIX Shared Memory
POSIX Shared Memory allows multiple processes to access the same physical memory region simultaneously. Instead of exchanging data through repeated system calls, processes communicate by reading and writing directly to a shared memory area created by the kernel. This makes shared memory one of the fastest Interprocess Communication (IPC) mechanisms available.
Learning Objectives
- Understand POSIX Shared Memory.
- Learn why it is the fastest IPC mechanism.
- Understand shared memory objects.
- Study memory mapping.
- Prepare for POSIX shared memory APIs.
1. What is POSIX Shared Memory?
POSIX Shared Memory is a kernel-managed IPC mechanism that enables multiple processes to map the same shared memory object into their virtual address spaces. Each process accesses the shared region using ordinary memory operations after mapping has been established.
2. Why Use Shared Memory?
| Requirement | Shared Memory Benefit |
|---|---|
| High Performance | Direct memory access. |
| Large Data Exchange | No repeated data copying. |
| Low Latency | Very fast communication. |
| Real-Time Systems | Minimal kernel overhead. |
| Shared Data Structures | Multiple processes view identical data. |
3. Why is Shared Memory the Fastest IPC?
Unlike pipes or message queues, data does not need to be copied between user space and kernel space for every transfer. After the shared memory region is mapped, processes communicate through normal memory reads and writes.
4. Shared Memory Architecture
Each process has its own virtual address space, but both virtual addresses reference the same physical memory pages.
5. Shared Memory Object
A POSIX shared memory object behaves similarly to a file. Processes create or open the object using its name and then map it into memory.
6. Memory Mapping Concept
The mmap() function establishes the mapping between the
shared memory object and the process's virtual address space.
7. Shared Memory Lifecycle
Creating a shared memory object is only the first step. Processes typically resize it, map it, access it, unmap it, close the file descriptor, and finally remove the object's name when it is no longer needed.
8. Linux Implementation
On Linux, POSIX shared memory objects are commonly implemented
using the tmpfs mounted at:
This is a Linux implementation detail. Portable applications should use only the POSIX shared memory APIs rather than relying on the filesystem representation.
9. Advantages
- Very high performance.
- Minimal kernel involvement after mapping.
- Suitable for large data transfers.
- Efficient for multimedia and scientific applications.
- Can be shared by unrelated processes.
10. Interview Questions
- What is POSIX Shared Memory?
- Why is shared memory considered the fastest IPC mechanism?
- How does shared memory differ from message queues?
- What is a shared memory object?
- Why is
mmap()required? - Can unrelated processes share the same memory object?
- Where are POSIX shared memory objects commonly implemented on Linux?
- What is the purpose of
shm_open()? - What happens after the memory is mapped?
- Why are synchronization mechanisms often required with shared memory?
11. shm_open()
The shm_open() function creates a new POSIX shared
memory object or opens an existing one.
The function returns a file descriptor that can later be resized
using ftruncate() and mapped into memory using
mmap().
12. shm_open() Parameters
| Parameter | Description |
|---|---|
name |
Shared memory object name beginning with '/'. |
oflag |
Creation and access flags. |
mode |
Permission bits (used with O_CREAT). |
13. Object Creation Flags
| Flag | Description |
|---|---|
O_CREAT |
Create the shared memory object if it does not exist. |
O_EXCL |
Fail if the object already exists. |
O_RDONLY |
Open for read-only access. |
O_RDWR |
Open for read/write access. |
14. ftruncate()
A newly created shared memory object has a length of zero bytes.
The ftruncate() function changes the object's size
before it can be used.
15. close()
After a shared memory object has been successfully mapped using
mmap(), the file descriptor is usually no longer
required and can be closed.
Closing the descriptor does not remove the memory mapping.
16. shm_unlink()
The shm_unlink() function removes the name associated
with a shared memory object.
The object itself remains available until all processes have
unmapped it and closed their file descriptors.
17. Shared Memory Permissions
| Permission | Description |
|---|---|
| 0400 | Owner Read |
| 0200 | Owner Write |
| 0040 | Group Read |
| 0020 | Group Write |
| 0004 | Others Read |
| 0002 | Others Write |
18. Example: Creating a Shared Memory Object
19. Linux Commands
| Command | Description |
|---|---|
ls /dev/shm |
List shared memory objects. |
mount | grep shm |
Verify tmpfs mount. |
man shm_open |
Shared memory object creation. |
man shm_unlink |
Shared memory cleanup. |
man ftruncate |
Resize object. |
20. Interview Questions
- Why does a newly created shared memory object have a size of zero bytes?
- Why is
ftruncate()called beforemmap()? - What does
shm_open()return? - What is the purpose of
O_CREAT? - What is the purpose of
O_EXCL? - Why can the file descriptor be closed after
mmap()? - What does
shm_unlink()remove? - Does
shm_unlink()immediately destroy the shared memory object? - Where are POSIX shared memory objects commonly stored on Linux?
- Which permissions are commonly used when creating a shared memory object?
21. mmap()
The mmap() function maps a shared memory object into
the calling process's virtual address space.
Once the mapping is established, the process accesses the shared
memory using ordinary pointer operations.
22. mmap() Parameters
| Parameter | Description |
|---|---|
addr |
Preferred virtual address (usually NULL). |
length |
Number of bytes to map. |
prot |
Memory protection flags. |
flags |
Mapping type. |
fd |
Shared memory file descriptor. |
offset |
Starting offset (normally 0). |
23. Memory Protection Flags
| Flag | Description |
|---|---|
PROT_READ |
Memory may be read. |
PROT_WRITE |
Memory may be modified. |
PROT_EXEC |
Memory may contain executable code. |
PROT_NONE |
No access permitted. |
24. Mapping Flags
| Flag | Description |
|---|---|
MAP_SHARED |
Changes are visible to all mapped processes. |
MAP_PRIVATE |
Copy-on-write private mapping. |
POSIX shared memory normally uses
MAP_SHARED because updates must be visible to all
participating processes.
25. Virtual Memory Mapping
Although each process has its own virtual address, both mappings refer to the same physical memory pages.
26. munmap()
The munmap() function removes a memory mapping from
the calling process.
After the mapping is removed, the process must no longer access
the memory region.
27. Example: Writer Process
The writer stores data directly into the mapped shared memory region.
28. Example: Reader Process
The reader accesses the same shared memory region and reads the data written by another process.
29. Shared Memory Access Flow
30. Linux Commands
| Command | Description |
|---|---|
man mmap |
Memory mapping documentation. |
man munmap |
Remove mapping documentation. |
man mprotect |
Memory protection management. |
cat /proc/<PID>/maps |
Display mapped memory regions. |
pmap <PID> |
Display process memory map. |
31. Advanced Interview Questions
- Why is
mmap()required aftershm_open()? - What does
MAP_SHAREDguarantee? - What is the difference between
MAP_SHAREDandMAP_PRIVATE? - Can two processes have different virtual addresses for the same shared memory?
- What happens if a process accesses memory after calling
munmap()? - What is the purpose of
PROT_READ? - When would
PROT_EXECbe used? - Why is
MAP_PRIVATEgenerally unsuitable for POSIX shared memory communication? - Does
mmap()copy the entire shared memory object into user space? - What Linux utilities help inspect mapped memory?
32. Shared Memory Lifecycle
A shared memory object is created or opened, resized, mapped into memory, accessed by one or more processes, then unmapped and finally removed when no longer needed.
33. Complete Communication Flow
34. Synchronization Requirement
Shared memory only provides a common storage area. It does not prevent two processes from modifying the same memory simultaneously. Synchronization mechanisms such as POSIX semaphores are commonly used to coordinate access.
35. Common Programming Mistakes
- Calling
mmap()beforeftruncate()on a newly created object. - Forgetting to call
munmap(). - Forgetting
shm_unlink(), leaving unused objects in the system. - Accessing shared memory after
munmap(). - Using
MAP_PRIVATEwhen data sharing is required. - Ignoring return values from system calls.
- Accessing shared memory without synchronization.
36. Best Practices
- Resize newly created objects with
ftruncate()before mapping. - Use
MAP_SHAREDfor interprocess communication. - Protect shared memory with semaphores or another synchronization mechanism.
- Check every API return value.
- Unmap memory before program termination.
- Remove shared memory objects with
shm_unlink()when they are no longer needed. - Keep shared data structures simple and well documented.
37. Debugging Tips
| Problem | Possible Cause |
|---|---|
| Segmentation Fault | Access after munmap(). |
| No shared data visible | Used MAP_PRIVATE. |
| Object already exists | Previous object not removed with shm_unlink(). |
| Mapping failed | Invalid size or permissions. |
| Corrupted data | Missing synchronization. |
38. Advanced Interview Questions
- Explain the lifecycle of a POSIX shared memory object.
- Why must
ftruncate()be called beforemmap()for a new object? - Why is synchronization required when using shared memory?
- What is the difference between
MAP_SHAREDandMAP_PRIVATE? - Why is
MAP_PRIVATEgenerally unsuitable for IPC? - Can multiple processes map the same shared memory object at different virtual addresses?
- What happens if a process accesses memory after
munmap()? - What does
shm_unlink()remove? - Why is
close()typically called after a successfulmmap()? - Which synchronization mechanisms are commonly used with shared memory?
39. Module Summary
In this module, we studied POSIX Shared Memory in detail.
We covered shared memory objects, object creation using
shm_open(), resizing with
ftruncate(), memory mapping using
mmap(), memory protection flags,
mapping flags, removing mappings with
munmap(), deleting shared memory objects using
shm_unlink(), synchronization requirements,
common mistakes, debugging techniques, and best practices.
POSIX Shared Memory provides one of the highest-performance IPC
mechanisms because processes exchange information through a shared
memory region rather than repeatedly transferring data through
the kernel.
Concept Mastery Assessment — Module 46
Verify your conceptual understanding with 12 targeted technical assessment questions. Instant feedback and explanations are provided for every choice.