Search topics...
Embedded LinuxIPCadvanced

Compare shared memory and Unix domain sockets for IPC.

0 upvotes
Practice with AISoon

Shared memory (shmget/shmat or POSIX shm_open/mmap) provides the highest-throughput IPC mechanism because data is never copied — both processes map the same physical memory pages into their virtual address spaces. A producer writes data directly into the shared region, and the consumer reads it with zero copies. This makes shared memory ideal for large data transfers: video frames, audio buffers, sensor data streams, or any scenario where copying megabytes per second through a pipe or socket would waste CPU cycles and memory bandwidth.

Unix domain sockets (AF_UNIX) provide a byte-stream or datagram interface similar to network sockets but confined to the local machine. Data is copied from the sender's buffer into the kernel and then into the receiver's buffer — two copies per message. This is slower than shared memory for bulk data but far simpler to program correctly. Sockets provide built-in synchronization (blocking read/write), flow control (the kernel buffers data and applies backpressure when the receiver is slow), and clean error handling (the sender gets EPIPE or ECONNRESET if the peer crashes).

The fundamental tradeoff is performance vs. safety and simplicity. Shared memory requires you to implement your own synchronization (semaphores, mutexes, or lock-free data structures) and your own signaling mechanism (often a Unix domain socket or eventfd just to notify the consumer that data is available). If you get the synchronization wrong, you have race conditions that are extremely difficult to debug. Unix domain sockets handle all of this for you. In embedded Linux systems, use shared memory only when profiling proves that the copy overhead of sockets is a bottleneck — for most IPC (commands, status updates, configuration), Unix domain sockets are simpler and sufficient.

Source: Embedded Linux Q&A