Notes
All notes

Inter-Process Communication (OS Core #8)

Processes are isolated by design, so sharing data between them needs an explicit channel. The kernel provides several, and they differ in direction, how much data they carry, whether they survive the processes, and how much copying they do.

The IPC toolbox

Mechanism Direction Related processes Persistence Cost
Pipe one-way parent/child (common ancestor) until closed copy through kernel
FIFO (named pipe) one-way any, via a path until unlinked copy through kernel
Message queue both ways, messages any, by name until removed copy, priority support
Shared memory both ways any, by name until removed no copy after setup
Socket both ways local or remote until closed copy + protocol stack
Signal notification only any, by pid delivered once very low, no data
Semaphore synchronisation any, by name until removed atomic counter

The choice is usually made for you by the problem: a shell pipeline is a pipe, a local service is a Unix socket, a database cache is shared memory, and a “reload your config” is a signal.

QQuestionWhy is shared memory faster than a pipe for large data?
ASolution

A pipe copies data into the kernel and out again (two copies). Shared memory maps the same frames into both address spaces, so a write is visible with no copy and no syscall.

Pipes

pipe() creates two descriptors: one for reading, one for writing. Data flows in one direction through a kernel buffer.

#include <unistd.h>
#include <sys/wait.h>
#include <cstdio>
#include <cstring>

int main() {
    int fds[2];
    if (pipe(fds) < 0) { std::perror("pipe"); return 1; }

    pid_t pid = fork();
    if (pid == 0) {
        close(fds[1]);                       // child only reads
        char buf[64];
        ssize_t n = read(fds[0], buf, sizeof buf - 1);
        if (n > 0) { buf[n] = 0; std::printf("child got: %s\n", buf); }
        close(fds[0]);
        _exit(0);
    }

    close(fds[0]);                           // parent only writes
    const char* msg = "hello";
    write(fds[1], msg, std::strlen(msg));
    close(fds[1]);                           // EOF for the child
    waitpid(pid, nullptr, 0);
}
\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, minimum width=1.6cm, minimum height=0.6cm, font=\scriptsize, align=center},
  a/.style={->, thick}]
  \node[b, fill=blue!10] (w) at (0,0) {writer};
  \node[b, fill=orange!18] (buf) at (3.2,0) {kernel buffer\64 KB};
  \node[b, fill=green!18] (r) at (6.4,0) {reader};
  \draw[a] (w) -- node[above, font=\tiny] {write()} (buf);
  \draw[a] (buf) -- node[above, font=\tiny] {read()} (r);
  \node[font=\scriptsize, anchor=north] at (3.2,-0.6) {blocks when full or empty};
\end{tikzpicture}

Behaviour worth knowing:

$ ls | grep txt | wc -l

The shell creates two pipes and connects the three processes with dup2.

QQuestionWhy does read on a pipe return 0 even though the writer never wrote

anything?

ASolution

Because the write end was closed. EOF on a pipe means “no writers left”, not “the writer sent zero bytes”.

Named pipes (FIFOs)

A FIFO has a path in the filesystem but behaves like a pipe. Unrelated processes can use it by opening the same path.

$ mkfifo /tmp/myfifo
$ echo hello > /tmp/myfifo &      # writer
$ cat /tmp/myfifo                 # reader
hello
mkfifo("/tmp/myfifo", 0666);
int fd = open("/tmp/myfifo", O_WRONLY);   // blocks until a reader opens it
write(fd, "hi", 2);
close(fd);

The FIFO has no storage on disk; the path is a rendezvous point. The data still goes through the kernel buffer, and the same blocking and atomicity rules apply. Opening for read or write blocks until the other side appears, unless O_NONBLOCK is used.

QQuestionWhat happens if a FIFO is opened O_RDWR by one process?
ASolution

It succeeds immediately and never sees EOF, because the process itself holds a write end. That is occasionally useful for a daemon, and usually a bug.

Message queues

A message queue carries discrete messages with priorities, not a byte stream. POSIX queues are named with a leading slash and persist until unlinked.

#include <mqueue.h>
#include <cstring>

mqd_t q = mq_open("/jobs", O_CREAT | O_RDWR, 0600, nullptr);
const char* msg = "build";
mq_send(q, msg, std::strlen(msg), 1);        // priority 1
mq_close(q);

// another process
mqd_t r = mq_open("/jobs", O_RDONLY);
char buf[64];
unsigned prio = 0;
ssize_t n = mq_receive(r, buf, sizeof buf, &prio);

Queues are good when message boundaries matter and you want the kernel to buffer them. Limits live in /proc/sys/fs/mqueue (maximum message size, maximum messages per queue).

Compared with a pipe: a queue keeps boundaries and priorities, and does not need a common ancestor. Compared with a socket: it is local only and simpler.

QQuestionWhy can a message queue be a bad fit for large payloads?
ASolution

Every message is copied into the kernel and out again, and queues have small size limits. For large data, shared memory plus a small notification is better.

Shared memory

Shared memory maps the same physical pages into two or more processes. It is the fastest IPC because after setup there are no syscalls and no copies.

#include <fcntl.h>
#include <sys/mman.h>
#include <semaphore.h>
#include <unistd.h>

struct Shared {
    sem_t lock;
    int value;
};

int fd = shm_open("/demo", O_CREAT | O_RDWR, 0600);
ftruncate(fd, sizeof(Shared));
auto* s = (Shared*)mmap(nullptr, sizeof(Shared),
                        PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
sem_init(&s->lock, 1, 1);        // 1 = shared between processes

Synchronisation is mandatory. Two processes writing the same field is the same data race as two threads, with the same consequences. Use a process-shared semaphore, a mutex with PTHREAD_PROCESS_SHARED, or atomics in the shared region.

Shared memory also has no lifetime management: if a process crashes while holding the semaphore, the others may block forever unless the lock is robust.

QQuestionWhat is the main risk of shared memory compared with a pipe?
ASolution

A pipe isolates the reader from the writer’s memory. Shared memory exposes the same bytes to both, so a bug in one process can corrupt the other’s data, and a crash can leave a lock held.

Sockets

A socket is a bidirectional endpoint. AF_UNIX is local (filesystem path or abstract name); AF_INET/AF_INET6 is the network.

// server
int srv = socket(AF_INET, SOCK_STREAM, 0);
sockaddr_in addr{};
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
addr.sin_port = htons(8080);
bind(srv, (sockaddr*)&addr, sizeof addr);
listen(srv, 128);
int client = accept(srv, nullptr, nullptr);

// client
int s = socket(AF_INET, SOCK_STREAM, 0);
connect(s, (sockaddr*)&addr, sizeof addr);

Sockets are the only IPC that works across machines, which is why they dominate service architecture. They also handle buffering, flow control, and connection state, which pipes and queues do not.

QQuestionWhy does a TCP server need listen before accept?
ASolution

listen marks the socket as accepting connections and sets the backlog size. Without it, the socket is not in the listening state and accept fails.

Signals

A signal is a small asynchronous notification delivered to a process. It carries no payload beyond a number.

#include <csignal>

volatile sig_atomic_t stop = 0;

void on_sigint(int) {
    stop = 1;                    // async-signal-safe: plain sig_atomic_t store
}

int main() {
    std::signal(SIGINT, on_sigint);
    while (!stop) { /* work */ }
}
Signal Default action Catchable?
SIGINT terminate (Ctrl-C) yes
SIGTERM terminate yes
SIGSEGV terminate + core yes, but usually fatal
SIGCHLD ignore yes
SIGKILL terminate no
SIGSTOP stop no

Rules for handlers:

SIGKILL and SIGSTOP cannot be caught or blocked, which is why kill -9 always works (except in uninterruptible sleep).

QQuestionWhy can a signal handler not call printf?
ASolution

printf uses internal locks and buffers that may be in an inconsistent state if the signal arrived inside another printf. It is not async-signal-safe, so the behaviour is undefined.

Semaphores for IPC

Named semaphores work across processes:

sem_t* sem = sem_open("/mysem", O_CREAT, 0600, 1);
sem_wait(sem);       // acquire
// critical section on shared memory
sem_post(sem);       // release
sem_close(sem);
sem_unlink("/mysem");

For a mutex that lives in shared memory, POSIX allows pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED). That gives you a real mutex, with owner tracking, instead of a counting semaphore.

QQuestionWhy is a process-shared mutex better than a binary semaphore for

protecting shared memory?

ASolution

A mutex has an owner. If the owner dies, a robust mutex can report EOWNERDEAD to the next locker. A semaphore has no owner, so a crash while holding it leaves the resource locked forever.

IPC versus shared-memory multithreading

Threads Processes + IPC
Address space shared separate
Communication direct memory syscalls / mappings
Cost per message nanoseconds microseconds
Fault isolation none strong
Crash impact whole process one process
Synchronisation mutexes, atomics semaphores, shared mutexes
Scaling limited by one address space across machines

Threads are cheaper until the sharing gets complicated or the isolation matters. A browser puts each tab in a process for exactly that reason: a crash in one tab does not take down the others.

QQuestionA service moves from threads to processes and gets slower

communicating. Why might it still be the right move?

ASolution

Isolation and fault containment. A crash or memory corruption stays in one process, and the service can restart it. The extra microseconds are the price of that guarantee.

Bugs and edge cases

QQuestionA pipe-based producer/consumer hangs after the consumer exits. What

is the likely cause?

ASolution

The producer is writing to a pipe with no readers, so it blocks forever (or gets SIGPIPE if the write happens after the reader closes). Check that all unused descriptor copies are closed.

Next: Advanced OS Concepts (OS Core #9) — virtualization, containers, NUMA, and the page cache.