Linux IPC mechanisms
Pipes, shared memory, sockets, message queues, signals and D-Bus.
Processes need to talk
An embedded Linux product is rarely one program. A typical gateway might run a sensor daemon, a cloud connector, a local web UI, an update agent and a watchdog supervisor, each a separate process for isolation: one crashing does not take the others down, and each can run with only the privileges it needs. Inter-process communication (IPC) connects them.
The options at a glance
| Mechanism | Data model | Direction | Between | Speed | Typical use |
|---|---|---|---|---|---|
| Pipe / FIFO | Byte stream | One way | Parent-child (pipe) or any (named FIFO) | Fast | Feeding one program's output to another |
| Unix domain socket | Stream or datagram | Two way | Any processes on the host | Fast | Daemons with clients; the default choice |
| Message queue (POSIX) | Messages with priority | Any | Any | Fast | Discrete messages, priorities |
| Shared memory | Raw memory | Any | Any | Fastest (no copy) | Large or high-rate data (video, sample buffers) |
| Signals | A number | One way | Any | — | Notifications: terminate, reload configuration |
| D-Bus | Method calls, signals, properties | Any | Via a bus daemon | Slower | System services (NetworkManager, BlueZ, systemd) |
| TCP/UDP sockets | Stream / datagram | Two way | Across machines too | Slower | When processes may run on different hosts |
| MQTT on localhost, gRPC, ZeroMQ | Messages | Any | Via broker or library | Varies | Higher-level designs |
Pipes and FIFOs
int fd[2];
pipe(fd); /* fd[0] read end, fd[1] write end */
if (fork() == 0) { /* child */
close(fd[0]);
write(fd[1], "ready\n", 6);
_exit(0);
}
close(fd[1]);
char buf[16];
ssize_t n = read(fd[0], buf, sizeof buf);
A FIFO (mkfifo /tmp/sensor.fifo) is a pipe with a name in the filesystem, so unrelated processes can use it. Both are one-way byte streams; writes of up to PIPE_BUF (4096 bytes on Linux) are atomic.
Unix domain sockets
The same sockets API as networking, but addressed by a filesystem path (or an abstract name) and staying inside the kernel, so faster than TCP. They support streams and datagrams, are bidirectional, work with select/poll/epoll, can check the peer's user ID (SO_PEERCRED), and can even pass open file descriptors between processes. For a daemon serving several clients, they are usually the best default.
int s = socket(AF_UNIX, SOCK_STREAM, 0);
struct sockaddr_un addr = { .sun_family = AF_UNIX };
strncpy(addr.sun_path, "/run/sensord.sock", sizeof addr.sun_path - 1);
connect(s, (struct sockaddr *)&addr, sizeof addr);
As with TCP, a stream socket has no message boundaries; frame your messages.
POSIX message queues
mq_open, mq_send, mq_receive: the kernel keeps discrete messages with priorities, and receivers block until one arrives. Useful when message boundaries and priorities matter and you do not want to write framing. Limits on queue length and message size are set per queue and system-wide.
Shared memory
int fd = shm_open("/frames", O_CREAT | O_RDWR, 0600);
ftruncate(fd, sizeof(struct frame_ring));
struct frame_ring *ring = mmap(NULL, sizeof *ring, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
Both processes see the same physical memory: no copying, the fastest possible transfer, ideal for camera frames or high-rate sample buffers. But shared memory provides no synchronisation: you must add it, using a process-shared mutex or semaphore (pthread_mutexattr_setpshared, sem_open), atomics with a lock-free single-producer single-consumer ring, or a separate notification channel (a socket or eventfd) to say "new data".
#include <stdio.h>
#include <stdint.h>
/* A single-producer, single-consumer ring of the kind placed in shared memory.
Each index is written by one side only, so no lock is needed (with atomics in real code). */
#define SLOTS 4
typedef struct { volatile uint32_t head, tail; int data[SLOTS]; } ring_t;
static int ring_put(ring_t *r, int v) {
if (r->head - r->tail == SLOTS) return -1; /* full */
r->data[r->head % SLOTS] = v;
r->head++; /* publish after the data is written */
return 0;
}
static int ring_get(ring_t *r, int *v) {
if (r->head == r->tail) return -1; /* empty */
*v = r->data[r->tail % SLOTS];
r->tail++;
return 0;
}
int main(void) {
ring_t shm = { 0 }; /* would come from mmap of a shm_open object */
for (int i = 1; i <= 5; i++) printf("producer put %d: %s\n", i * 10, ring_put(&shm, i * 10) ? "full" : "ok");
int v;
while (ring_get(&shm, &v) == 0) printf("consumer got %d\n", v);
return 0;
}
On real multi-core hardware, use C11 atomics with release/acquire ordering for the indexes, so the data write is visible before the index update.
Signals
Signals are asynchronous notifications identified by a number: SIGTERM (please exit), SIGINT (Ctrl-C), SIGHUP (conventionally "reload configuration"), SIGCHLD (a child exited), SIGUSR1/2 (application-defined). Handlers run asynchronously, interrupting the program anywhere, so they may only call async-signal-safe functions; the safe pattern is to set a volatile sig_atomic_t flag, or use signalfd to receive signals as file-descriptor events in the main loop. Signals carry no data and are not suitable for general communication.
D-Bus
D-Bus is a message bus: processes connect to a bus daemon (the system bus or a session bus), expose objects with interfaces containing methods, signals and properties, and call each other by well-known names (org.freedesktop.NetworkManager). It adds introspection, access-control policies and service activation.
On embedded Linux you will mostly use D-Bus to talk to existing system services: BlueZ (Bluetooth), NetworkManager or ConnMan (networking), systemd (services, logind), ModemManager. Libraries: sd-bus (systemd), GDBus (GLib), dbus-cxx. It is heavier than sockets, so for your own high-rate data, prefer sockets or shared memory.
Choosing
- One daemon, several clients, request/response or events: Unix domain sockets.
- Large, high-rate data between two processes: shared memory plus a notification (eventfd or socket).
- Talking to system services: D-Bus.
- Simple pipelines and parent-child: pipes.
- Lifecycle notifications: signals (via
signalfd). - Processes that may later move to another machine or language: a network protocol (MQTT, gRPC).
Pitfall: A writer to a pipe or socket whose reader has exited receives
SIGPIPE, which by default kills the writer. Daemons should ignoreSIGPIPE(or useMSG_NOSIGNAL) and handle theEPIPEerror instead.
Interview question: Which IPC mechanism would you choose for a sensor daemon that serves readings to several client processes, and why?
Answer: Unix domain sockets. They are bidirectional, support many concurrent clients through accept, integrate with poll or epoll in the daemon's event loop, are faster than TCP because they stay in the kernel, can authenticate clients by user ID with SO_PEERCRED, and use filesystem permissions for access control. Use a simple framed message protocol on top. If the readings were very high-rate bulk data, add shared memory for the data with the socket used for control and notification.
Interview question: How should a daemon handle SIGTERM safely?
Answer: Signal handlers interrupt the program at arbitrary points and may only call async-signal-safe functions, so the handler should only set a volatile sig_atomic_t flag (or write to a self-pipe), and the main loop checks it and shuts down cleanly: finishing or rolling back current work, flushing data and closing resources. Even better, block the signal and receive it through signalfd as an ordinary file descriptor in the poll loop. Under systemd, also make sure shutdown completes within the stop timeout.
Build it: requests and replies between the daemons
This is step 5 of the module project, the smart-home gateway. Two daemons share the work: the cloud daemon talks to the owner's phone, and the Zigbee daemon talks to the lamps. When the owner taps "living room off", the cloud daemon sends a request over a Unix domain socket and waits for the reply. Lamps go offline, the Zigbee daemon restarts, replies arrive twice or after the phone has given up: each request needs an id, a deadline and exactly one outcome.
Lab: Match replies to requests, with ids and deadlines
The cloud daemon keeps at most MAX_PENDING requests waiting for a reply.
rpc_send(r, now_ms, timeout_ms)registers a new request and returns its id, or -1 whenMAX_PENDINGare already waiting. Ids count up from 1 usinglast_id; after 65535 they wrap to 1, because 0 is never an id (the Zigbee daemon uses 0 for messages that are not replies). Skip any id that is still waiting. The request's deadline isnow_ms + timeout_ms.rpc_reply(r, id, now_ms)handles a reply. Return 0 when it answers a waiting request in time, and free that request. Return -2 for a reply that arrives after the deadline, and free the request too (the phone has been told it failed; do not act on it now). Return -1 for an id that is not waiting: a duplicate, or one already expired.rpc_expire(r, now_ms)frees every waiting request whose deadline has passed and returns how many. A deadline has passed whennow_msis later than it; compare the wrap-safe way,(int32_t)(now_ms - deadline) > 0, as the millisecond clock wraps after 49 days.
Going deeper
Interview question: How would you let a smart TV's video player, remote-control service and network service cooperate?
Answer: Run them as separate processes with clear ownership, talking over D-Bus or Unix domain sockets for commands and events, and shared memory with a synchronised ring buffer only where large data (video frames) must move without copying. Each service can then crash and restart without taking the others down.
Interview question: What is eventfd and how is it used with shared memory?
Answer: eventfd is a file descriptor that holds a 64-bit counter: writes add to it, reads return and reset it, and it becomes readable when non-zero. Paired with shared memory, the producer writes data to the shared region and then writes to the eventfd; the consumer waits on the eventfd with poll or epoll alongside its other descriptors, then reads the new data, so no busy polling is needed.
Interview question: Why are D-Bus calls unsuitable for high-rate data?
Answer: Every message goes through the bus daemon, which marshals, routes and copies it and checks policies, adding latency and CPU overhead per message. That is fine for control and configuration but inefficient for streams such as audio or sensor data at kilohertz rates; those should use shared memory or sockets, with D-Bus only for setup.
Explain it: In your own words, explain why Unix domain sockets are a good default for communication between processes on a device.
Answer: They use the same familiar sockets API as networking but stay inside the kernel, so they are faster than TCP over the loopback. They are bidirectional, support many clients connecting to one server, work with poll or epoll in an event loop, and use file permissions on the socket path for access control, with the ability to check the connecting process's user. They can also pass open file descriptors. For most daemon-and-client designs, that covers what is needed without the complexity of shared memory or the overhead of D-Bus.