Skip to content
systemcoding.dev
Systems Programming

IPC Mechanisms Compared: Pipes, Sockets, Shared Memory and Queues

Compare Linux IPC options for beginners: pipes, FIFOs, Unix sockets, shared memory, message queues, semaphores and signals, and which fits which job.

7 min read
Summarize in AI
Flat illustration of user space above the system call boundary, the kernel and the hardware, with the Linux, FreeBSD and GNU logos.

Two programs on one machine need to exchange data, and Linux offers a dozen ways to do it. The documentation for each reads as though it is the obvious answer, which is no help when you must pick. This post compares the mechanisms side by side, in plain terms for someone who has not used most of them, and ends with a short rule for choosing. It covers Linux 6.12 with glibc 2.41 and follows the overview in ipc(2) and svipc(7), plus mq_overview(7) and shm_overview(7).

The full treatment of the three kernel-object families is in the complete guide to shared memory, semaphores and message queues, and pipes have their own guide. Here you get the map.

Two questions decide most of it

Before comparing features, answer two questions about your problem.

Do the processes share an ancestor, or are they strangers? Related processes, such as a parent and the children it forks, can inherit descriptors and mappings, which makes pipes and anonymous shared memory possible. Unrelated processes, started independently, need a name they both know: a file path, a socket path, a shared-memory name or a numeric key.

Is it a stream of bytes, a stream of messages or a shared state? A log being forwarded is a stream. A request for a service is a message. A table of counters that several processes update is shared state. Each of the three has a natural mechanism, and forcing the wrong one produces the awkward code that makes people give up on IPC.

The mechanisms in one table

MechanismShapeWho can connectDirectionBoundaries kept
PipeStreamRelated processesOne wayNo
FIFO (named pipe)StreamAny, by pathOne wayNo
Unix domain socket, streamStreamAny, by pathTwo wayNo
Unix domain socket, datagram or seqpacketMessagesAny, by pathTwo wayYes
TCP or UDP on loopbackStream or messagesAny, by portTwo wayTCP no, UDP yes
POSIX message queueMessagesAny, by nameMany to manyYes, with priorities
System V message queueMessagesAny, by keyMany to manyYes, with types
Shared memory, POSIX or System VShared stateAny, by name or keyBothNot applicable
SemaphoreSignaling onlyAny, by name or keyNot dataNot applicable
SignalNotification, tiny payloadAny, by PIDOne wayNot applicable
Regular fileStream or stateAny, by pathBothNot applicable

A semaphore is on the list because it is the usual partner of shared memory, not because it moves data. Signals carry no data except for real-time signals with one machine word.

Pipes and FIFOs

A pipe is a kernel buffer with a read end and a write end. It is the right tool for the simplest case, a parent feeding a child or a pipeline of filters, and it is what the shell uses. A FIFO is the same buffer given a filesystem name so unrelated processes can use it. Both are byte streams, one direction, and both block the writer when the buffer is full, which gives you flow control for free.

pipe_min.cc
int fd[2];
pipe(fd);                       /* fd[0] reads, fd[1] writes */

Pick them for one-way data between related processes or for glueing programs together. How Unix pipes work explains the rules.

Unix domain sockets

A Unix domain socket looks like a network socket but stays on one machine and is named by a path. It is two-way, supports many clients through accept(), and has variants that keep message boundaries (SOCK_SEQPACKET and SOCK_DGRAM). It can also pass open file descriptors and the sender's credentials between processes, which nothing else here can do.

unix_min.cc
int s = socket(AF_UNIX, SOCK_STREAM, 0);

If you are building a local service that several clients talk to, this is the default choice. It costs a little more per call than a pipe and gives you structure in return.

Shared memory

Shared memory maps the same physical pages into two processes, so a write by one is a read by the other with no system call in between. It is the fastest way to share a large amount of data, and the only one that does not copy. It also gives you nothing else: no notification, no flow control, no way to tell that the other process died. You must add a semaphore or similar to coordinate, and you must design the data layout so both sides agree on it.

shm_min.cc
int fd = shm_open("/demo", O_CREAT | O_RDWR, 0600);
ftruncate(fd, 4096);
void *p = mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);

Use it for big buffers, shared tables and caches. Share memory between processes with shm_open and mmap is the next step.

Message queues

A message queue stores discrete messages, each with a priority (POSIX) or a type (System V), in a kernel object named by the application. Senders and receivers need not exist at the same time, because the queue holds messages until they are read. Several senders and several receivers are normal. POSIX queues also report readiness through poll(), select() and epoll on Linux, which makes them fit into event loops. System V queues do not.

mq_min.cc
mqd_t q = mq_open("/jobs", O_CREAT | O_RDWR, 0600, NULL);

Pick one when the data is a sequence of separate messages and the sender and the receiver should be decoupled. See send messages between processes with POSIX mq_send and mq_receive.

Semaphores

A semaphore is a counter that processes decrement to wait and increment to signal. It moves no data. It protects shared memory or orders actions between processes, for example "do not read before the writer is done". POSIX semaphores come named, for unrelated processes, or unnamed, placed inside shared memory. System V semaphores come in sets with atomic multi-semaphore operations.

Signals

A signal tells a process that something happened. Standard signals carry no data and collapse when several arrive, and real-time signals queue and carry one integer. They suit "reload your configuration" or "stop", and they are a poor channel for data. Send data with real-time signals and sigqueue covers the exception.

Files, and why not to dismiss them

A regular file is IPC too: one process appends and the other reads, or each rewrites a status file. It needs no special API, survives restarts and works across machines on a network filesystem. Its weaknesses are no notification, so the reader has to poll or use inotify, and the lack of atomic updates unless you write to a temporary file and rename() it. For configuration and slow-changing state, a file with an atomic rename is often the best answer.

How the data moves

How many times the bytes are copied, and how many system calls each message costs, differs by mechanism, and that is what makes shared memory fast and everything else similar to each other. Pipes vs Unix sockets vs shared memory goes into the measurement. Do not choose by speed until you know the speed matters, because the features, such as boundaries, flow control, naming and failure detection, decide most real projects.

A short decision rule

  1. Parent and child, one direction: a pipe.

  2. A local service with several clients or two-way chat: a Unix domain socket.

  3. Messages to be queued and read later, possibly by someone else: a POSIX message queue.

  4. A large block of data or a table that both sides read and write: shared memory plus a semaphore.

  5. A "wake up" or "stop": a signal, or better an eventfd or a pipe.

  6. Slow-changing state or configuration: a file with an atomic rename.

Which API family: POSIX or System V

For queues, semaphores and shared memory there are two parallel APIs. System V is older and works everywhere, with numeric keys and tools like ipcs. POSIX is newer, uses names that look like paths and plugs into file descriptors better. POSIX IPC vs System V IPC gives the full comparison, and our default is POSIX for anything new.

Lifetime: what outlives your program

A pipe disappears when the last descriptor closes. A Unix socket's path stays in the filesystem until you unlink() it. Shared memory, message queues and semaphores, in both families, persist after every process using them has exited, until someone removes them or the machine reboots. That is useful for state that survives restarts and a hazard for leaks. List and remove stale IPC objects with ipcs and ipcrm shows the cleanup.

Shell
ls /dev/shm /dev/mqueue
ipcs
Text
/dev/mqueue:
jobs

/dev/shm:
demo

------ Message Queues --------
key        msqid      owner      perms      used-bytes   messages

------ Shared Memory Segments --------
key        shmid      owner      perms      bytes      nattch     status

------ Semaphore Arrays --------
key        semid      owner      perms      nsems

The listing shows POSIX objects under /dev/shm and /dev/mqueue, and System V objects through ipcs. Names and the empty System V tables here are an example, and your system will show its own contents.

When none of these is right

If the two sides run on different machines, use a network protocol. If many consumers must each see every message, a broadcast, use a socket-based publish scheme or a ring buffer designed for it, because a pipe and a queue deliver each item to one reader only. If one process runs several threads, use ordinary memory with a mutex and a condition variable, which is simpler than any inter-process mechanism.

Share

Keep reading

Flat illustration of two options weighed side by side, with the macOS, Linux and Apple logos.
Kernels

Mach Traps vs BSD System Calls on macOS

Learn how macOS routes one trap instruction to either a Mach trap or a BSD system call, how the number sign and class decide, and why you should call libSystem.

8 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.