shared memory as the fastest IPC
Every other form of IPC copies bytes: the sender hands data to the kernel, the kernel hands a copy to the receiver. Shared memory removes the copying entirely. The kernel arranges for the same physical pages of RAM to appear in two processes' address spaces at once. Now when one process writes a number into that region, the other process sees it instantly, because they are literally looking at the same bytes. It is two people writing on the same physical whiteboard rather than mailing each other photos of their own.
There are two common ways to set it up. The older System V style: shmget() creates or finds a shared segment by a numeric key, and shmat() attaches it into your address space at some pointer. The POSIX/modern style: shm_open() gives you a file-descriptor-like handle to a named shared object, you size it with ftruncate(), then mmap() it into memory. Either way the result is the same: a block of memory, say 1 MiB, that both processes can read and write through ordinary pointers — char *p — with no system call per access. Because there is no kernel involved once it is mapped, shared memory is the fastest IPC there is.
But that speed comes with the catch that defines it: the kernel no longer mediates each access, so it gives you no synchronization. If two processes write the same location at once, or one reads while the other is half-finished writing, you get a data race and garbage — exactly the same hazard as two threads sharing memory. You must add your own coordination: a mutex or semaphore placed in shared memory, or atomic operations. So shared memory is not 'easy fast IPC' — it is 'raw fast memory plus a synchronization problem you now own.' Use it when you move a lot of data and can manage the locking; reach for a pipe or socket when you just want simple, safe message passing.
int fd = shm_open("/buf", O_CREAT|O_RDWR, 0600); ftruncate(fd, 4096); int *shared = mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); shared[0] = 42; /* another process that maps "/buf" sees 42 with no copy */
Map the same object MAP_SHARED in two processes and a plain pointer write is visible to both — instantly, and unsynchronized.
Shared memory gives you speed but no safety: the kernel does not serialize access, so concurrent writes are a data race exactly like threads sharing memory. You must add a mutex, semaphore, or atomics yourself.