Home Knowledge Base POSIX Shared Memory and Memory-Mapped Files

POSIX Shared Memory and Memory-Mapped Files are the inter-process communication (IPC) mechanisms that allow multiple processes to access the same region of physical memory — providing the fastest possible data sharing between processes on the same machine (zero-copy, no kernel involvement after setup), essential for high-performance computing, database engines, ML inference serving, and any application where microsecond-level IPC latency matters.

Shared Memory vs. Other IPC

IPC MethodLatencyThroughputComplexity
Shared memory (mmap/shm)~100 nsMemory bandwidthMedium
Unix domain socket~1-5 µs~5 GB/sLow
TCP/IP (localhost)~10-50 µs~2-5 GB/sLow
Pipe/FIFO~1-5 µs~3-5 GB/sLow
Message queue (POSIX)~5-10 µs~1-3 GB/sMedium

POSIX Shared Memory API

#include <sys/mman.h>
#include <fcntl.h>

// Process A: Create shared memory
int fd = shm_open("/my_shm", O_CREAT | O_RDWR, 0666);
ftruncate(fd, 4096);  // Set size
void *ptr = mmap(NULL, 4096, PROT_READ | PROT_WRITE,
                 MAP_SHARED, fd, 0);
// Write data
memcpy(ptr, data, sizeof(data));

// Process B: Attach to same region
int fd = shm_open("/my_shm", O_RDONLY, 0666);
void *ptr = mmap(NULL, 4096, PROT_READ, MAP_SHARED, fd, 0);
// Read data — zero copy, same physical pages

Memory-Mapped Files

// Map a file into memory
int fd = open("large_dataset.bin", O_RDONLY);
void *data = mmap(NULL, file_size, PROT_READ,
                  MAP_PRIVATE, fd, 0);
// Access file as if it were memory
double value = ((double*)data)[1000000];
// OS handles page faults → loads from disk on demand

Key Differences

Featureshm_open (POSIX SHM)mmap (file-backed)
Backingtmpfs (RAM only)Filesystem (disk/SSD)
PersistenceUntil shm_unlink or rebootPersistent on disk
Size limitAvailable RAMDisk space
Use caseFast IPCLarge dataset access, persistence
Survives rebootNoYes (file persists)

Synchronization

ML / Data Pipeline Usage

Huge Pages for Performance

POSIX shared memory and memory-mapped files are the foundation of zero-copy IPC on modern systems — by allowing multiple processes to directly access the same physical memory pages without kernel-mediated data copies, they provide the highest possible throughput for local inter-process data sharing, making them indispensable for ML inference pipelines, database engines, and any high-performance system where data must flow between processes at memory bandwidth speeds.

shared memory ipcposix shared memorymemory mapped filemmapshm_openinterprocess communication

Explore 500+ Semiconductor & AI Topics

From EUV lithography to CUDA optimization — search the full knowledge base or chat with our AI assistant.