Operating Systems Module 4: Concurrency Lesson 4.5 12 min

Processes talking

Processes have separate memory, so they need the kernel’s help to talk: pipes for streams of bytes, shared memory for speed, signals for tapping on the shoulder, and sockets for everything else.

When you type ls | wc -l, two programs that know nothing about each other cooperate: one lists files, the other counts lines. How does the output of one get into the other? They are separate processes, each with its own address space (Lesson 2.1), so neither can read the other’s variables. Whatever passes between them has to go through the kernel.

That is inter-process communication, or IPC. There are a handful of mechanisms, each with its own trade-off.

Pipes

A pipe is a one-way channel made of a buffer inside the kernel. One process writes bytes at one end, and another reads them at the other end, in the same order. The shell builds ls | wc -l by creating a pipe and connecting the first program’s output to its write end, and the second program’s input to its read end.

The buffer has a limited size, and that gives a pipe a very useful behaviour: it makes a fast writer wait for a slow reader. This simulation uses a tiny pipe that holds 8 bytes, so you can see it happen. Real pipes are bigger, but work the same way.

A pipe that fills up

  1. Start: an empty pipe Two processes are connected by a pipe: a buffer that lives in the kernel, here holding at most 8 bytes. What one process writes, the other reads, in the same order. Real pipes are bigger, but they work the same way.
    Pipe holds
    0 of 8 bytes
    Pipe contents
    (empty)
    Writer
    running
    Reader
    running
  2. The writer fills most of the pipe Writer calls write with "abcdef" (6 bytes). The kernel copies the bytes into the pipe's buffer, and write returns at once. The pipe holds 6 of 8.
    Pipe holds
    6 of 8 bytes
    Pipe contents
    "abcdef"
    Writer
    running
    Reader
    running
  3. The writer tries to add more: the writer blocks Writer calls write with "ghijk" (5 bytes), but only 2 bytes of the pipe is free. A write is not allowed to leave half of its data behind here, so the kernel puts Writer to sleep until a reader makes room. The writer is stuck, and uses no CPU.
    Pipe holds
    6 of 8 bytes
    Pipe contents
    "abcdef"
    Writer
    asleep (blocked)
    Reader
    running
  4. The reader makes room Reader calls read for up to 4 bytes and gets "abcd" (4 bytes). Those bytes leave the pipe, which now holds 2 of 8. Writer was asleep in its write. There is room now, so the kernel wakes it and its 5 bytes ("ghijk") go into the pipe.
    Pipe holds
    7 of 8 bytes
    Pipe contents
    "efghijk"
    Writer
    running
    Reader
    running
  5. The reader reads again Reader calls read for up to 4 bytes and gets "efgh" (4 bytes). Those bytes leave the pipe, which now holds 3 of 8.
    Pipe holds
    3 of 8 bytes
    Pipe contents
    "ijk"
    Writer
    running
    Reader
    running

The bytes came out in exactly the order they went in: abcd, then efgh, with the blocked writer’s ghijk after them. A pipe is a stream: it has no message boundaries, it is just bytes in order. The same thing happens on an empty pipe, the other way round: a reader that asks for data sleeps until a writer provides some.

What does a reader do when the writer has finished? It cannot wait forever. When the writer closes its end and the pipe is empty, read returns 0 bytes. That is end of file, and it is how wc knows the input is over.

Closing the write end

  1. Start: an empty pipe Two processes are connected by a pipe: a buffer that lives in the kernel, here holding at most 8 bytes. What one process writes, the other reads, in the same order. Real pipes are bigger, but they work the same way.
    Pipe holds
    0 of 8 bytes
    Pipe contents
    (empty)
    Writer
    running
    Reader
    running
  2. The writer sends a word Writer calls write with "bye" (3 bytes). The kernel copies the bytes into the pipe's buffer, and write returns at once. The pipe holds 3 of 8.
    Pipe holds
    3 of 8 bytes
    Pipe contents
    "bye"
    Writer
    running
    Reader
    running
  3. The writer is finished Writer closes its end of the pipe. Data already in the pipe stays there, so the reader can still read it. Once the pipe is empty the reader will get end of file instead of waiting.
    Pipe holds
    3 of 8 bytes
    Pipe contents
    "bye"
    Writer
    closed its end
    Reader
    running
  4. The reader asks for 8 bytes Reader calls read for up to 8 bytes and gets "bye" (3 bytes). Those bytes leave the pipe, which now holds 0 of 8.
    Pipe holds
    0 of 8 bytes
    Pipe contents
    (empty)
    Writer
    closed its end
    Reader
    running
  5. The reader asks again The pipe is empty, and every writer has closed it, so no more data can ever arrive. read returns 0 bytes: end of file. A reader's loop stops when it sees this.
    Pipe holds
    0 of 8 bytes
    Pipe contents
    (empty)
    Writer
    closed its end
    Reader
    running

Here is a pipe between a parent and its child in C. pipe makes the two ends, fork gives both processes a copy of them (Lesson 2.3), and each process closes the end it does not use. The parent writes, the child reads.

pipe.c
#include <stdio.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>

int main(void) {
    int fd[2];                          /* fd[0] reads, fd[1] writes */
    pipe(fd);
    if (fork() == 0) {                  /* child: the reader */
        close(fd[1]);                   /* it will not write */
        char buf[32];
        ssize_t n = read(fd[0], buf, sizeof buf - 1);   /* sleeps until data arrives */
        buf[n] = '\0';
        printf("child read: %s\n", buf);
        return 0;
    }
    close(fd[0]);                       /* parent: the writer, will not read */
    write(fd[1], "hello", strlen("hello"));
    close(fd[1]);
    wait(NULL);                         /* wait for the child to finish */
    printf("parent: child is done\n");
    return 0;
}

Output (one run)

child read: hello
parent: child is done

The output order is fixed. The child cannot print before it has read, and the parent waits for the child before printing its own line. Closing the unused ends matters: a reader only sees end of file once every copy of the write end is closed.

Signals

A signal is a tiny message from the kernel to a process, with no data except which signal it is. It interrupts the process, a bit like a hardware interrupt does the CPU. When you press Ctrl+C, the terminal sends SIGINT to the running program. When a program touches memory it should not, it gets SIGSEGV. kill sends signals, and despite the name, most signals do not kill anything.

For each signal a process can choose: run its own handler function, ignore it, or leave the default action, which for SIGINT is to terminate. Here a program installs a handler first, and then receives Ctrl+C.

Ctrl+C with a handler

  1. Start A program is running, and another process (a shell) can send it signals: small messages from the kernel that interrupt the program.
    Shell
    running
    Program
    running
  2. The program installs a handler Program installs a handler for SIGINT: a function of its own for the kernel to call when that signal arrives, instead of the default action.
    Shell
    running
    Program
    running
  3. The program is busy working Program keeps running its own code.
    Shell
    running
    Program
    running
  4. You press Ctrl+C Shell asks the kernel to send SIGINT to Program. The kernel does not run anything yet: it only marks the signal as pending for Program. It is acted on the next time Program is about to run.
    Shell
    running
    Program
    running, pending: SIGINT
  5. The kernel delivers the signal The kernel delivers SIGINT. Program has a handler, so the kernel interrupts what the program was doing, runs the handler, and then lets the program carry on from where it was. The program decides what to do about the signal.
    Shell
    running
    Program
    running

There is one signal no process can do anything about: SIGKILL. A process cannot catch it, block it or ignore it, and the kernel ends the process without running any of its code. That is what makes kill -9 the last resort when a program is stuck. Try the SIGKILL scenario in Try it on the simulator above: the program ignores SIGINT with no problem, but when it asks to catch SIGKILL, the kernel refuses.

signal.c
#include <signal.h>
#include <stdio.h>
#include <unistd.h>

void on_usr1(int sig) {
    (void)sig;
    write(1, "handler ran\n", 12);      /* write is safe inside a handler; printf is not */
}

int main(void) {
    signal(SIGUSR1, on_usr1);           /* install the handler */
    raise(SIGUSR1);                     /* send the signal to ourselves */
    printf("main carries on\n");
    return 0;
}

Output (one run)

handler ran
main carries on

Shared memory and sockets

A pipe copies the data twice: from the writer into the kernel, and from the kernel into the reader. For large amounts of data that is wasteful. Shared memory asks the kernel to map the same physical memory into two processes’ address spaces, so what one writes, the other sees at once, with no system call and no copy. It is the fastest IPC there is. But it brings back everything from the start of this module: the two processes now share data, so they need locks or semaphores of their own to avoid races. The kernel does not protect you any more.

Sockets are like pipes that work in both directions and between machines. A socket can connect two processes on the same computer (a Unix domain socket, which the database on your laptop probably uses) or across the internet (TCP). They are slower than a pipe, but they are how a browser talks to a server, and the same code works whether the other end is next door or on another continent.

Mechanism Good for Remember
Pipe A stream between related processes, like a shell pipeline One direction, a bounded buffer, a slow reader makes the writer wait
Shared memory Large data, the highest speed You must synchronise it yourself
Signal A short notification: stop, reload, user interrupt Carries no data and can arrive at any time
Socket Two-way, over a network or locally Slower, but works between machines

In the real world

Every shell pipeline is a chain of pipes. On Linux, a pipe holds 64 KiB by default; this program asks the kernel:

pipe_size.c
#define _GNU_SOURCE
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>

int main(void) {
    int fd[2];
    pipe(fd);
    printf("this pipe holds %d bytes\n", fcntl(fd[1], F_GETPIPE_SZ));
    return 0;
}

Output (one run)

this pipe holds 65536 bytes

Databases such as PostgreSQL let their server processes share a big region of shared memory for the buffer cache, with locks around it. systemctl reload and kill -HUP ask a daemon to re-read its configuration with a signal. And Docker’s tools talk to the Docker daemon through a Unix socket. :::

Quick check

Quick check

  1. A process writes to a pipe whose buffer is full. What happens?
  2. What does read return when the pipe is empty and every write end has been closed?
  3. Which signal can a process not catch, block or ignore?
  4. When is shared memory a better choice than a pipe, and what is the catch?

Recap

  • Processes have separate address spaces, so IPC goes through the kernel.
  • A pipe is a bounded byte stream: a full pipe blocks the writer, an empty one blocks the reader, and closing every write end gives the reader end of file.
  • A signal is a small message that interrupts a process. It may catch or ignore most signals (the default for SIGINT is to terminate). SIGKILL cannot be caught.
  • Shared memory is the fastest but needs its own synchronisation. Sockets work in both directions and across networks.

Next: a project. A small bank has three bugs, and you will find and fix each of them with what you learned in this module.

Your progress is saved in this browser. Sign in to keep it on every device. Free, no password.

Join the discussion