Inter Process Communication in Linux: IPC Methods Explained

Inter Process Communication in Linux_ IPC Methods Explained

Inter process communication in Linux is the way separate processes share data and signal each other through the kernel. The main methods are pipes and FIFOs, POSIX and System V message queues, shared memory, UNIX domain and network sockets, signals, and semaphores. Use pipes for simple parent-child streams, sockets for flexible client-server designs, message queues for small prioritized messages, and shared memory (guarded by a semaphore or mutex) when you need the highest throughput and lowest latency.

Open a terminal on any embedded Linux board and run ps -e. You will see dozens of processes: a logger, a network manager, a sensor daemon, maybe a GUI. None of them can touch each other’s memory, yet your product only works if they cooperate.

That cooperation is inter process communication in Linux, usually shortened to IPC. It is the set of kernel-provided mechanisms (pipes, message queues, shared memory, sockets, signals and semaphores) that let isolated processes exchange data and coordinate their actions.

In this guide you will learn how each mechanism works, when to pick it, how to write working C code for it, and which mistakes cost engineers days of debugging on real hardware.

Why Is Inter Process Communication in Linux Important?

Linux gives every process its own virtual address space, enforced by the MMU. That isolation is a feature: a crash in your display process cannot corrupt your motor-control process.

But isolation creates a problem. Real products are built from several cooperating programs, and those programs need controlled doors between them. IPC is that set of doors.

Here is what a good IPC design gives you:

  • Modularity: split a large firmware application into small processes (acquisition, processing, UI, cloud uplink) that you can build and test independently.
  • Fault isolation: if the UI process crashes, systemd can restart it while the data logger keeps running.
  • Privilege separation: only the small process that touches hardware needs device access or root; everyone else talks to it through a narrow interface.
  • True parallelism: on multi-core SoCs such as the Raspberry Pi or NXP i.MX family, separate processes run on separate cores at the same time.
  • Replaceability: a clean IPC interface lets you swap one component without rewriting the rest.

Field note: teams that start with one giant process usually split it later, under deadline pressure. Designing the IPC boundaries early is far cheaper.

registor_now_P

Core Concepts

Get these terms clear before choosing a mechanism:

  • Process: a running program with its own virtual address space, file descriptor table and credentials.
  • User space vs kernel space: processes cannot read each other’s memory directly. They ask the kernel through system calls such as read(), write() and mmap().
  • File descriptor (fd): a small integer handle. Pipes, FIFOs, sockets, eventfds and POSIX message queues are all fds on Linux, so they work with poll() and epoll().
  • Synchronization: coordination that stops one process from reading data while another is halfway through writing it.
  • Race condition: a bug where the result depends on unpredictable timing between processes.
  • Blocking vs non-blocking: whether a call sleeps until it can finish, or returns immediately with an error such as EAGAIN.
  • Persistence: how long the IPC object lives: until the process exits, until reboot, or until someone removes it explicitly.

Message Passing vs Shared Memory

Every IPC mechanism follows one of two models.

  • Message passing: the sender copies data into a kernel object, and the receiver copies it out. The kernel handles buffering and most of the synchronization. The cost is two copies and a system call on each side.
  • Shared memory: the kernel maps the same physical pages into both address spaces. After setup, communication is a plain memory read or write, with no system call and no copy. In return, you own all the synchronization.

A useful rule of thumb: start with message passing because it is easier to get right, and move to shared memory only when measurements show the copy cost matters.

Working Principle

Here is what actually happens inside the kernel for the two models.

Message passing (anonymous pipe example)

  1. Process A calls write(fd, data, len). The kernel copies the bytes from A’s user buffer into a kernel pipe buffer.
  2. If the pipe buffer is full, A sleeps until the reader makes room.
  3. Process B calls read(fd, buf, len). The kernel copies the bytes from the pipe buffer into B’s user buffer and wakes A if space was freed.
  4. When every write end is closed, B’s read() returns 0. That is how B learns the stream has ended (EOF).

Shared memory (POSIX example)

  1. shm_open() creates a named memory object, which lives in the tmpfs mounted at /dev/shm.
  2. ftruncate() sets its size.
  3. mmap() with MAP_SHARED maps the object into each process. The virtual address can differ in each process, but the physical pages are the same.
  4. Both processes now load and store directly. A semaphore or mutex decides who may touch the data and when.

Architecture

Think of Linux IPC as three layers: isolation at the bottom, kernel IPC objects in the middle, and your application protocol on top.

 Process A (user space)                   Process B (user space)
+----------------------+                +----------------------+
| write()  send()      |                | read()  recv()       |
| mq_send()  kill()    |                | mq_receive()         |
+----------+-----------+                +-----------^----------+
           | system call                            | system call
===========|========================================|=========== kernel boundary
           v                                        |
+--------------------------------------------------------------+
|                   Linux kernel IPC subsystem                 |
| pipe buffers | POSIX mqueue | socket buffers | signal delivery |
+--------------------------------------------------------------+
           ^                                        ^
           |   shared memory: same physical pages   |
           +------------ mapped into both ----------+

Points worth remembering about this architecture:

  • Isolation layer: the MMU and page tables keep each process in its own address space. IPC is the only legal way across.
  • Where objects live: pipe, socket and message queue buffers live inside the kernel. Shared memory pages are ordinary RAM pages mapped into more than one process.
  • Naming: FIFOs and UNIX sockets use filesystem paths. POSIX shared memory appears under /dev/shm. POSIX message queues can be browsed under /dev/mqueue once that filesystem is mounted. System V objects use numeric keys and IDs.
  • Containers matter: IPC namespaces (CLONE_NEWIPC) isolate System V IPC and POSIX message queues between containers. Docker also gives each container its own /dev/shm, typically 64 MB by default, which surprises many people running shared-memory workloads.

Features

What makes Linux IPC a strong toolbox:

  • Many mechanisms, each tuned for a different mix of latency, throughput and complexity.
  • Kernel-enforced permissions: pipes, FIFOs, POSIX shared memory, message queues, semaphores and sockets all honor user, group and mode bits.
  • fd-based integration: one epoll() loop can wait on sockets, pipes, timers and message queues together.
  • Blocking and non-blocking modes, plus timed variants such as mq_timedreceive() and sem_timedwait().
  • Message priorities in message queues.
  • Local and networked communication with the same socket API.
  • Passing file descriptors and credentials over UNIX domain sockets (SCM_RIGHTS, SO_PEERCRED).
  • Good observability through /proc, ipcs, lsof, ss and strace.

Types of IPC Mechanisms in Linux

Linux IPC mechanisms fall into four families:

  • Data transfer: pipes, FIFOs, message queues, sockets.
  • Shared memory: POSIX shared memory, System V shared memory, memory-mapped files.
  • Synchronization: semaphores, process-shared mutexes, futexes, file locks.
  • Notification: signals, eventfd, mq_notify().

There are also two API generations. POSIX IPC is modern, name based and fd friendly. System V IPC is older and key based. For new code, prefer POSIX unless you are maintaining legacy software.

1. Anonymous Pipes

  • Created with pipe(), which returns two file descriptors: one for reading, one for writing.
  • A unidirectional byte stream, normally shared between related processes because the fds are inherited through fork().
  • Default capacity on Linux is 64 KiB. Writes up to PIPE_BUF (4096 bytes on Linux) are atomic, so they never interleave with another writer’s data.
  • Best for: shell pipelines such as ls | grep c, or a parent collecting output from a child.
  • Watch out: close the pipe ends you do not use, or the reader never sees EOF.

2. Named Pipes (FIFOs)

  • Created with mkfifo() or the mkfifo command. The FIFO appears as a special file in the filesystem.
  • Unrelated processes can communicate by opening the same path.
  • open() blocks until both a reader and a writer exist, unless you use O_NONBLOCK.
  • Still a one-way byte stream. For two-way traffic, use two FIFOs.
  • Best for: feeding commands from a shell script into a long-running daemon.

3. POSIX Message Queues

  • API: mq_open(), mq_send(), mq_receive(), mq_close(), mq_unlink(). Queue names start with a slash, for example /sensor_q.
  • Messages keep their boundaries (no manual framing) and carry a priority. Higher priority messages are received first.
  • Each queue has a maximum message count and message size. System-wide caps live in /proc/sys/fs/mqueue/, and the defaults are small (typically 10 messages of up to 8192 bytes).
  • On Linux the queue descriptor is a real fd, so it works with poll() and epoll(). mq_notify() can also notify you when a message arrives.
  • Best for: commands, events and small structured messages that need priority.

4. System V IPC (Message Queues, Semaphores, Shared Memory)

  • API families: msgget()/msgsnd()/msgrcv(), semget()/semop(), shmget()/shmat().
  • Objects are identified by an integer key, often generated with ftok().
  • They persist until removed with ipcrm or until reboot, which makes stale objects common after crashes.
  • They are not file descriptors, so you cannot put them into epoll().
  • Best for: maintaining legacy code. Prefer POSIX equivalents in new projects.

5. Shared Memory

  • POSIX route: shm_open() + ftruncate() + mmap(MAP_SHARED). System V route: shmget() + shmat(). You can also share an anonymous mmap() across fork(), or use memfd_create() and pass the fd to another process.
  • The fastest mechanism because there is no copy after setup.
  • It has no built-in synchronization. You must add semaphores, mutexes or lock-free techniques.
  • Never store raw pointers inside shared memory. Each process may map it at a different address, so use offsets or indexes.
  • Best for: camera frames, audio buffers, large sensor arrays and ring buffers.

6. Semaphores, Mutexes and Futexes

  • They carry no data. They decide who may touch the data and when.
  • POSIX semaphores come in two forms: named (sem_open()) and unnamed (sem_init() with pshared=1, placed inside shared memory).
  • Mutexes can be shared across processes with PTHREAD_PROCESS_SHARED. Add PTHREAD_MUTEX_ROBUST so a waiting process can recover if the owner dies while holding the lock.
  • For real-time systems, add PTHREAD_PRIO_INHERIT to avoid priority inversion.
  • Under the hood, fast user-space locking is built on the futex() system call. File locks (flock(), fcntl()) are another option.

7. Sockets (UNIX Domain and Network)

  • UNIX domain sockets (AF_UNIX) work only on one machine. They are bidirectional and are addressed by a filesystem path or an abstract name.
  • They support SOCK_STREAM, SOCK_DGRAM and SOCK_SEQPACKET (reliable, with message boundaries).
  • They can pass open file descriptors between processes (SCM_RIGHTS) and report the peer’s user and process ID (SO_PEERCRED).
  • Network sockets (AF_INET, AF_INET6) extend the same API across machines with TCP or UDP.
  • Best for: client-server daemons. Because the socket API is the same, a design that starts local can later become networked with small changes.

8. Signals

  • Lightweight asynchronous notifications sent with kill() and handled with sigaction().
  • Standard signals do not queue. If the same signal arrives twice before it is handled, the process may see it only once.
  • Real-time signals (SIGRTMIN to SIGRTMAX) do queue, and sigqueue() can attach a small integer or pointer value.
  • Inside a handler, call only async-signal-safe functions.
  • Best for: requests such as shutdown (SIGTERM) or reload (SIGHUP). Do not use signals to carry data.

9. D-Bus and Other Higher-Level Frameworks

  • D-Bus is a message bus daemon built on top of sockets. It offers service names, method calls, broadcast signals, introspection and access policy.
  • systemd, NetworkManager and BlueZ expose their interfaces through D-Bus.
  • It is convenient but adds overhead, so do not push bulk or high-rate data through it.
  • Other higher-level options include Android’s Binder, MQTT, ROS 2 (DDS) and gRPC.

Advantages

  • Modular design: components can be built, tested, updated and restarted independently.
  • Kernel-enforced isolation and permissions reduce the blast radius of a bug.
  • Right tool for each job: from a signal that costs almost nothing to shared memory that moves gigabytes per second.
  • Mature, standardized APIs: POSIX interfaces behave consistently across Linux distributions and Yocto-based images.
  • Excellent tooling: ipcs, lsof, ss, strace and /proc make IPC objects visible.
  • Scales outward: sockets let the same design span a board, a gateway and the cloud.

Limitations

  • Choice overload: picking the wrong mechanism early can force a painful rewrite.
  • Synchronization is hard: shared memory without correct locking produces rare, timing-dependent bugs.
  • Copy and context-switch cost: message passing adds system calls and copies, which can matter at high rates.
  • Weak protection with shared memory: a stray write in one process can corrupt data used by another.
  • Resource limits: pipe size, message queue limits, /dev/shm size and fd limits can all cause failures that only appear in the field.
  • Lifecycle problems: named objects can outlive a crashed process and leave stale state behind.
  • Portability: details differ between POSIX and System V, and between Linux and other UNIX systems.

Real-World Applications

Here is how IPC shows up in real products:

  • Automotive: Linux-based infotainment platforms split the UI, media player, navigation and connectivity into separate services. They typically talk over D-Bus and UNIX domain sockets, so a navigation crash does not stop audio playback.
  • Medical devices: a patient monitor often runs an acquisition process that writes ECG or SpO2 samples into a shared memory ring buffer. Display and alarm processes read from it independently, so a slow screen never delays the sensor loop.
  • Consumer electronics: smart TVs and set-top boxes hand video frames to the compositor through shared buffers whose file descriptors are passed over UNIX sockets. Wayland uses exactly this pattern.
  • Industrial automation: a soft-PLC runtime, an HMI and a Modbus or CAN gateway run as separate processes. Shared memory holds the process image, while message queues carry commands.
  • Aerospace and ground systems: Linux-based telemetry software often separates parsing, storage and downlink into independent processes joined by queues and sockets, so one stage can be restarted or upgraded without stopping the others.
  • Robotics: each ROS 2 node is a separate process. Some DDS implementations switch to a shared memory transport when nodes run on the same machine.
  • IoT gateways: protocol adapters (BLE, Zigbee, Modbus) feed a bridge process that publishes to the cloud over MQTT. UNIX sockets or message queues connect the pieces on the gateway.
  • Smart home: a hub uses BlueZ, which exposes Bluetooth through D-Bus, alongside other daemons that coordinate through sockets.
  • Wearables: Android-based wearables rely on Binder, Android’s own IPC mechanism, while Linux-based ones lean on D-Bus and sockets.
  • Multi-core SoCs: on parts that pair Cortex-A cores running Linux with a Cortex-M core running an RTOS (STM32MP1 and i.MX 8 are common examples), Linux talks to the microcontroller core through RPMsg over shared memory, using the remoteproc and OpenAMP frameworks.

 

Explore Courses - Learn More

Workflow: How to Choose and Implement IPC

Use this checklist every time you add a new communication path between two processes:

  1. Describe the traffic. Note the message size, messages per second, number of senders and receivers, and the latency you can tolerate.
  2. Pick the mechanism.
    • Small control messages: UNIX domain socket or POSIX message queue.
    • Byte stream between related processes: pipe.
    • Large or high-frequency data: shared memory plus a semaphore or eventfd.
    • Communication across machines: TCP or UDP sockets.
    • One-line events such as reload or shutdown: signals.
  3. Define the message format. Use fixed-width types (uint32_t), a version field, explicit lengths and a stated byte order. Never send pointers.
  4. Plan synchronization. Decide who may read or write at each moment, and what happens when the reader is slower than the writer.
  5. Plan the lifecycle. Decide who creates the object, who removes it, and what happens after a crash or restart.
  6. Handle errors. Cover EINTR, EAGAIN, partial reads and writes, and timeouts (poll(), mq_timedreceive(), sem_timedwait()).
  7. Test under stress and failure. Kill a peer with kill -9, fill the buffers, and start the processes in a different order.

Code Examples and Explanation

The two examples below compile on any Linux system with gcc, including Ubuntu, Raspberry Pi OS and Yocto images that ship a toolchain.

Example 1: Anonymous Pipe Between Parent and Child

/* pipe_demo.c - parent sends a sensor reading to its child */
#include 
#include 
#include 
#include 
#include <sys/wait.h>

int main(void)
{
    int fd[2];                      /* fd[0] = read end, fd[1] = write end */
    char buf[64];

    if (pipe(fd) == -1) {
        perror("pipe");
        return EXIT_FAILURE;
    }

    pid_t pid = fork();
    if (pid == -1) {
        perror("fork");
        return EXIT_FAILURE;
    }

    if (pid == 0) {
        /* Child: reader */
        close(fd[1]);               /* close the unused write end */
        ssize_t n = read(fd[0], buf, sizeof(buf) - 1);
        if (n > 0) {
            buf[n] = '\0';
            printf("Child received: %s\n", buf);
            fflush(stdout);         /* _exit() does not flush stdio buffers */
        }
        close(fd[0]);
        _exit(EXIT_SUCCESS);
    }

    /* Parent: writer */
    close(fd[0]);                   /* close the unused read end */
    const char *msg = "temp=27.5C";
    if (write(fd[1], msg, strlen(msg)) == -1) {
        perror("write");
    }
    close(fd[1]);                   /* closing the write end signals EOF */
    wait(NULL);
    return EXIT_SUCCESS;
}

Build and run

gcc -Wall -Wextra -o pipe_demo pipe_demo.c
./pipe_demo
Expected output: Child received: temp=27.5C

Code explanation

  • pipe(fd) creates the kernel buffer and returns two descriptors.
  • fork() duplicates the descriptor table, so parent and child both hold both ends.
  • Each side immediately closes the end it will not use. This is what makes EOF detection work.
  • The parent closes fd[1] after writing. With every write end closed, a reader’s read() returns 0.
  • A pipe is a byte stream. One write() does not guarantee one matching read(), so production code loops until it has the bytes it expects.

Common errors

  • The child forgets close(fd[1]). It then holds a write end open itself, so it can wait forever for EOF after the parent finishes.
  • Writing to a pipe whose read end is closed raises SIGPIPE and kills the process unless you handle or ignore it.
  • Assuming message boundaries exist. They do not in pipes. A related trap sits in the child: _exit() skips stdio flushing, so without fflush(stdout) the message can vanish when output is redirected to a file or another pipe.

Example 2: Shared Memory With POSIX Semaphores (Producer and Consumer)

This example mirrors a common embedded pattern: one process samples a sensor, another consumes the data. Two named semaphores form a classic single-slot handshake: slot_free (starts at 1) and data_ready (starts at 0).

ipc_common.h

#ifndef IPC_COMMON_H
#define IPC_COMMON_H

#include 

#define SHM_NAME  "/iies_sensor_shm"
#define SEM_FREE  "/iies_sem_free"
#define SEM_READY "/iies_sem_ready"

/* Fixed-width fields keep the layout identical in both processes */
typedef struct {
    uint32_t sequence;
    float    temperature_c;
    float    humidity_pct;
} sensor_sample_t;

#endif

producer.c

/* producer.c - writes sensor samples into shared memory */
#include 
#include 
#include 
#include 
#include <sys/mman.h>
#include 
#include "ipc_common.h"

int main(void)
{
    /* 1. Create (or open) the shared memory object and size it */
    int fd = shm_open(SHM_NAME, O_CREAT | O_RDWR, 0600);
    if (fd == -1) { perror("shm_open"); return EXIT_FAILURE; }
    if (ftruncate(fd, sizeof(sensor_sample_t)) == -1) {
        perror("ftruncate");
        return EXIT_FAILURE;
    }

    /* 2. Map it into this process's address space */
    sensor_sample_t *shared = mmap(NULL, sizeof(*shared),
                                   PROT_READ | PROT_WRITE,
                                   MAP_SHARED, fd, 0);
    if (shared == MAP_FAILED) { perror("mmap"); return EXIT_FAILURE; }
    close(fd);                      /* the mapping stays valid */

    /* 3. Open the semaphores: slot free (1) and data ready (0) */
    sem_t *slot_free  = sem_open(SEM_FREE,  O_CREAT, 0600, 1);
    sem_t *data_ready = sem_open(SEM_READY, O_CREAT, 0600, 0);
    if (slot_free == SEM_FAILED || data_ready == SEM_FAILED) {
        perror("sem_open");
        return EXIT_FAILURE;
    }

    /* 4. Produce five samples */
    for (uint32_t i = 1; i <= 5; i++) { sem_wait(slot_free); /* wait for an empty slot */ shared->sequence      = i;
        shared->temperature_c = 25.0f + 0.5f * (float)i;
        shared->humidity_pct  = 60.0f - (float)i;
        sem_post(data_ready);                   /* announce new data */
        printf("Producer: wrote sample %u\n", (unsigned)i);
        sleep(1);
    }

    munmap(shared, sizeof(*shared));
    sem_close(slot_free);
    sem_close(data_ready);
    return EXIT_SUCCESS;
}

consumer.c

/* consumer.c - reads sensor samples from shared memory */
#include 
#include 
#include 
#include 
#include <sys/mman.h>
#include 
#include "ipc_common.h"

int main(void)
{
    int fd = shm_open(SHM_NAME, O_CREAT | O_RDWR, 0600);
    if (fd == -1) { perror("shm_open"); return EXIT_FAILURE; }
    if (ftruncate(fd, sizeof(sensor_sample_t)) == -1) {
        perror("ftruncate");
        return EXIT_FAILURE;
    }

    sensor_sample_t *shared = mmap(NULL, sizeof(*shared),
                                   PROT_READ | PROT_WRITE,
                                   MAP_SHARED, fd, 0);
    if (shared == MAP_FAILED) { perror("mmap"); return EXIT_FAILURE; }
    close(fd);

    sem_t *slot_free  = sem_open(SEM_FREE,  O_CREAT, 0600, 1);
    sem_t *data_ready = sem_open(SEM_READY, O_CREAT, 0600, 0);
    if (slot_free == SEM_FAILED || data_ready == SEM_FAILED) {
        perror("sem_open");
        return EXIT_FAILURE;
    }

    for (int n = 0; n < 5; n++) { sem_wait(data_ready); /* sleep until data arrives */ printf("Consumer: seq=%u temp=%.1f C hum=%.1f %%\n", (unsigned)shared->sequence,
               shared->temperature_c,
               shared->humidity_pct);
        sem_post(slot_free);                    /* hand the slot back */
    }

    /* The consumer owns cleanup: remove the names from the system */
    munmap(shared, sizeof(*shared));
    sem_close(slot_free);
    sem_close(data_ready);
    sem_unlink(SEM_FREE);
    sem_unlink(SEM_READY);
    shm_unlink(SHM_NAME);
    return EXIT_SUCCESS;
}

Build and run (the -lrt flag is only needed on older glibc versions and is harmless on newer ones)

gcc -Wall -Wextra -o producer producer.c -pthread -lrt
gcc -Wall -Wextra -o consumer consumer.c -pthread -lrt

./consumer      # terminal 1
./producer      # terminal 2

Expected consumer output:

Consumer: seq=1 temp=25.5 C hum=59.0 %
Consumer: seq=2 temp=26.0 C hum=58.0 %
Consumer: seq=3 temp=26.5 C hum=57.0 %
Consumer: seq=4 temp=27.0 C hum=56.0 %
Consumer: seq=5 temp=27.5 C hum=55.0 %

Code explanation

  • shm_open() creates a memory object under /dev/shm. ftruncate() gives it a size, because a new object starts with zero bytes.
  • mmap() with MAP_SHARED maps those pages into the process. Writes by one process are visible to the other.
  • Both programs use O_CREAT, so it does not matter which one starts first. The initial semaphore values apply only to whichever process actually creates them.
  • sem_wait(slot_free) blocks the producer until the consumer has finished with the slot. sem_post(data_ready) wakes the consumer. This handshake guarantees the consumer never reads a half-written struct.
  • The shared struct uses fixed-width types, so the layout is identical in both processes.
  • The consumer calls sem_unlink() and shm_unlink() so the names do not linger in /dev/shm after the run.

Common errors

  • Forgetting ftruncate(). Writing into an unsized object causes SIGBUS.
  • Skipping the semaphores. The consumer can then read a struct while the producer is updating it, producing torn values that appear only occasionally.
  • Leftover objects after a crash. A stale sem.iies_sem_free in /dev/shm may carry a wrong counter into the next run. Remove the stale files with rm /dev/shm/sem.iies_* /dev/shm/iies_sensor_shm.
  • Ignoring EINTR. sem_wait() can return early when a signal arrives, so production code retries in a loop.
MechanismDirectionUnrelated processes?Data copied?Relative speedExtra synchronization?Typical use
Anonymous pipeOne-wayNormally noYesGoodNoShell pipelines, parent-child streams
FIFOOne-wayYesYesGoodNoScript-to-daemon feed
POSIX message queueAny process with accessYesYesGoodNoPrioritized commands and events
Shared memoryBoth waysYesNo (after setup)FastestYesFrames, large buffers, ring buffers
UNIX domain socketTwo-wayYesYesVery goodNoLocal client-server services
TCP or UDP socketTwo-wayYes, across machines tooYesLimited by the networkNoRemote services
SignalOne-way notificationYesNo data (RT signals carry a small value)Very fast, tiny payloadNot applicableReload, shutdown
D-BusTwo-wayYesYesModerateNoSystem services, infotainment control

How to read the table:

  • Need raw speed for large data: choose shared memory.
  • Need simplicity and two-way traffic on one machine: choose a UNIX domain socket.
  • Need message priority or built-in boundaries: choose a POSIX message queue.
  • Need to cross a machine boundary: choose TCP or UDP sockets.
FeaturePOSIX IPCSystem V IPC
NamingPath-like name such as /myqInteger key from ftok()
DescriptorFile descriptor (works with poll() and epoll())Not a file descriptor
API styleSimple, file-likeOlder and more complex
PersistenceUntil unlinked or rebootUntil removed with ipcrm or reboot
Inspectionls /dev/shm, /dev/mqueueipcs, ipcrm
RecommendationPreferred for new codeLegacy maintenance

Best Practices

Design

  • Pick the simplest mechanism that meets the requirement. A UNIX socket that is fast enough beats a clever shared-memory scheme that is hard to debug.
  • Treat every IPC boundary as an interface: document the owner, message layout, version, timeouts and failure behavior, the way a datasheet documents a peripheral.
  • Use a versioned message format with fixed-width types (uint32_t, not int or long) and a stated byte order. Add static_assert(sizeof(msg_t) == N, …) so layout changes break the build, not the field.

Coding

  • Check every return value. Handle EINTR, EAGAIN and partial reads or writes.
  • Give every blocking call a timeout (poll(), mq_timedreceive(), sem_timedwait()) so a dead peer cannot hang your process forever.
  • Prefer one epoll() event loop over one thread per channel. It is easier to reason about and cheaper on small SoCs.
  • Use robust, process-shared mutexes when processes share data structures, and handle EOWNERDEAD.

Reliability

  • Decide which process creates and which removes each named object. Clean stale objects at startup, for example from a systemd ExecStartPre step.
  • Test failure paths: kill a peer mid-message, fill the queue, start processes in the wrong order, restart one side repeatedly.

Security

  • Use restrictive permissions (0600 or 0660) on shared memory, queues and sockets. Place UNIX sockets under /run//.
  • Verify the peer with SO_PEERCRED when only certain users or services may connect.
  • Never trust lengths, offsets or indexes received from another process. Validate them before use, exactly as you would validate network input.
  • Follow MISRA C guidelines where your safety standard requires them, for example in automotive work governed by ISO 26262.

Common Mistakes

Each of these shows up regularly in code reviews and bring-up sessions.

1. Forgetting to Close Unused Pipe Ends

  • Why it happens: fork() copies every descriptor, and beginners forget the extra copies exist.
  • Impact: the reader never sees EOF, so the program hangs for no visible reason.
  • How professionals avoid it: close the unused ends right after fork(), and create pipes with pipe2(fd, O_CLOEXEC) so descriptors do not leak across exec().

2. Sharing Memory Without Synchronization

  • Why it happens: it appears to work in quick tests, because collisions are rare on a lightly loaded board.
  • Impact: torn reads and corrupted structs that show up once in thousands of runs, usually in front of a customer.
  • How professionals avoid it: pair every shared region with a semaphore or process-shared mutex, or use a carefully designed lock-free ring buffer with C11 atomics and correct memory ordering.

3. Storing Pointers in Shared Memory

  • Why it happens: a pointer that is valid in the creating process feels natural to share.
  • Impact: the other process maps the region at a different address, so the pointer leads to a segmentation fault or silent corruption.
  • How professionals avoid it: store offsets or array indexes relative to the start of the region.

4. Leaving Named Objects Behind

  • Why it happens: a crash or Ctrl+C skips the cleanup code.
  • Impact: stale semaphore counts, old data, File exists errors on the next run, and a slowly filling /dev/shm.
  • How professionals avoid it: keep one clear owner, handle SIGINT and SIGTERM with a cleanup path, and remove stale objects at startup.

5. Ignoring EINTR and Partial Transfers

  • Why it happens: lab tests rarely deliver signals or large payloads.
  • Impact: random failures and truncated messages in the field.
  • How professionals avoid it: wrap I/O in helper functions such as read_all() and write_all() that retry on EINTR and loop until the full length is transferred.

6. Using Signals to Carry Data

  • Why it happens: kill() looks like a quick way to tell another process something.
  • Impact: standard signals can merge, so events are lost, and handlers may call only async-signal-safe functions.
  • How professionals avoid it: use signals only as a wake-up or request, and send the actual data through a queue or socket. Inside an event loop, signalfd() turns signals into ordinary readable events.

7. Undersized Receive Buffers on Message Queues

  • Why it happens: mq_receive() requires a buffer at least as large as the queue’s mq_msgsize, which is easy to overlook.
  • Impact: the call fails with EMSGSIZE, which looks like a mysterious bug.
  • How professionals avoid it: call mq_getattr() and size the buffer from the result, and check the limits in /proc/sys/fs/mqueue/ and ulimit -q before deployment.

Debugging Tips

When two processes misbehave together, the bug is usually in the gap between them. These tools let you see that gap:

  • ls -l /dev/shm lists POSIX shared memory objects and named semaphores (they appear as sem.).
  • mount -t mqueue none /dev/mqueue then ls /dev/mqueue shows POSIX message queues. Reading a queue file reports its size and notification setup.
  • ipcs -a and ipcrm inspect and remove System V objects.
  • ls -l /proc//fd or lsof -p show which pipes, sockets and FIFOs a process holds. Matching pipe inode numbers in two processes prove they share the same pipe.
  • ss -xp lists UNIX domain sockets with their owning processes.
  • strace -f -tt -p reveals which system call each process is blocked in. Add -e trace=read,write,sendmsg,recvmsg,futex to cut the noise, or -e trace=ipc for System V calls.
  • cat /proc//wchan shows what the kernel is making a sleeping process wait on.
  • dbus-monitor or busctl monitor watch D-Bus traffic.
  • gdb with thread apply all bt shows whether a hung process is stuck in sem_wait(), read() or a mutex.
  • Add sequence numbers and checksums to messages so lost, repeated or torn data is detected immediately.
  • Timestamp both sides with CLOCK_MONOTONIC to measure real end-to-end latency instead of guessing.

Field note: ThreadSanitizer and Helgrind understand threads inside one process, not separate processes sharing a mapping. For cross-process shared memory, rely on code review, assertions and stress tests that run for hours.

Performance Optimization Tips

  • Match the mechanism to the payload: shared memory for bulk or high-rate data, sockets or message queues for small messages.
  • Batch small messages into one write() or send() to cut system call overhead.
  • Resize pipes when needed: fcntl(fd, F_SETPIPE_SZ, size) can raise capacity up to the limit in /proc/sys/fs/pipe-max-size for unprivileged processes.
  • Never busy-wait. Block on a semaphore, futex, eventfd or epoll() so the CPU can sleep. This also saves power on battery devices.
  • Use a single-producer, single-consumer ring buffer for high-rate shared memory. Use C11 atomics with acquire and release ordering, and keep the head and tail indexes on separate 64-byte cache lines to avoid false sharing.
  • Avoid user-space copies with splice(), vmsplice() and sendfile() when moving data between file descriptors.
  • Control scheduling for real-time work: sched_setaffinity() pins processes to cores, mlockall() prevents page faults, and pre-touching shared buffers at startup (or using MAP_POPULATE) removes first-access delays.
  • Prevent priority inversion with PTHREAD_PRIO_INHERIT on process-shared mutexes, especially on PREEMPT_RT kernels.
  • Measure before you optimize. perf, strace -c and timestamps will show the real bottleneck, which is often not where you expect.

 

Talk to Academic Advisor

Conclusion

Inter process communication in Linux is a toolbox, not a single feature. The skill is matching the mechanism to the job.

Key takeaways:

  • Use pipes and FIFOs for simple byte streams.
  • Use POSIX message queues for small, prioritized messages with clear boundaries.
  • Use UNIX domain sockets for flexible local client-server designs, and TCP or UDP when you must cross machines.
  • Use shared memory plus synchronization when throughput and latency matter most.
  • Use signals only for notifications, never for data.
  • Always plan lifecycle, cleanup, timeouts and error handling before you write the first line of code.

The fastest way to make this knowledge stick is to build the two examples above, break them on purpose, and debug them with strace and ls /dev/shm. If you want guided, hands-on practice with embedded Linux and system programming, explore the embedded systems training at the Indian Institute of Embedded Systems (IIES) in Bangalore.

FAQs

Inter process communication in Linux is the set of kernel mechanisms that let separate processes exchange data and coordinate their work. Because each process has its own virtual address space, they cannot read each other’s memory directly. IPC methods such as pipes, message queues, shared memory, sockets, signals and semaphores provide safe, controlled paths between them.

Linux offers anonymous pipes, named pipes (FIFOs), POSIX and System V message queues, POSIX and System V shared memory, semaphores and mutexes for synchronization, UNIX domain and network sockets, and signals. Higher-level options such as D-Bus build on these primitives. You choose based on data size, speed, direction and whether the processes are related.

Shared memory is the fastest because, once mapped, processes read and write the same physical pages with no system call or data copy. The trade-off is that you must add synchronization yourself, using semaphores, mutexes or lock-free techniques. For small messages, that extra complexity is rarely worth it, and a UNIX domain socket is often fast enough.

A pipe is an unstructured byte stream, so message boundaries are not preserved, and it normally connects related processes. A POSIX message queue stores discrete messages with priorities, keeps boundaries intact, and can be opened by unrelated processes using a name. Choose a pipe for simple streams and a message queue for structured, prioritized messages.

Use ipcs -a to list System V queues, semaphores and shared memory, and ipcrm to remove them. Inspect POSIX shared memory and named semaphores in /dev/shm, and mount mqueue on /dev/mqueue to see POSIX queues. Use ss -xp for UNIX sockets, and lsof or /proc/PID/fd to see which pipes a process holds.

Author

Embedded Systems and IOT Trainer– IIES

Updated On: 27-11-26


10+ years of hands-on experience delivering practical training in Embedded Systems and it's design