🧠 What is Shared Memory?
Shared Memory is an IPC mechanism where two or more processes map the same region of physical memory into their own address spaces, allowing them to directly read/write data without going through the kernel every time.
This is the fastest IPC method because it avoids system calls after setup.
🔁 How Shared Memory Works
-
One process creates a shared memory segment using a system call (e.g.,
shmgetin Linux). -
Other processes attach to that same segment (
shmat). -
Now all processes can read and write to the same memory region.
But here’s the catch:
There’s no built-in synchronization — you must use semaphores, mutexes, or spinlocks to avoid race conditions.
📦 Characteristics of Shared Memory
| Feature | Description |
|---|---|
| ⚡ Speed | Very fast (direct memory access) |
| 🧠 Visibility | Changes are instantly visible to other processes |
| 🚫 Risk | Can cause data races, corruption without locks |
| 🪢 Sync Required | Yes — must use semaphores, locks, or atomic ops |
| 📚 Setup Overhead | Needs initial coordination via system calls |
| 🌍 Scope | Can work across unrelated processes on the same machine |
🛠️ Common APIs (Linux example)
| Function | Purpose |
|---|---|
shmget() | Create shared memory segment |
shmat() | Attach shared memory to process |
shmdt() | Detach shared memory |
shmctl() | Control operations (delete, info) |
🔍 Code Snippet (C - Linux Style)
int id = shmget(IPC_PRIVATE, 1024, IPC_CREAT | 0666);
char *data = (char *) shmat(id, NULL, 0);
strcpy(data, "Hello from Process A");
// Process B reads from the same segmentBut you’ll also need a semaphore or mutex to control access.
🧠 Real-World Analogy
Imagine a whiteboard in a shared room. Everyone can write/read from it.
But without rules, two people might overwrite each other’s notes — that’s why you need a marker-passing protocol (like a semaphore).
🔄 Shared Memory vs Other IPCs
| Feature | Shared Memory | Pipes / Queues |
|---|---|---|
| 🔁 Performance | Very high | Medium (kernel copies) |
| 🪢 Synchronization | Manual (you must handle) | Automatic (OS-managed) |
| 📤 Setup Overhead | Medium | Low |
| 📍 Use Case | High-throughput, low-latency | Simpler communication |
🧠 Interview-Ready Definition:
Shared Memory is a high-performance IPC mechanism that allows multiple processes to share a portion of physical memory for direct communication. It requires explicit synchronization and is commonly used when speed and data sharing are critical.