Part 5 of 6 · 3 min read
Communication
Other ways for processes to talk
In plain words: Processes have separate address spaces (page 1), so they cannot touch each other's variables. The kernel provides several channels, each with a different cost and shape:
| Channel | Shape | Best for |
|---|---|---|
| Pipe | One-way byte stream between related processes | Shell pipelines, parent and child |
| Named pipe (FIFO) | The same, with a name in the file system | Unrelated processes on one machine |
| Signal | A number, with no data | Simple events such as "stop" or "reload" |
| Shared memory | A block of memory mapped into several processes | Very fast sharing of large data (Level 7) |
| Message queue | Separate messages with boundaries | Passing discrete messages |
| Socket | Two-way, works on one machine or across a network | Servers and clients |
| File | Data kept on disk | Slow exchange that must survive a crash |
The first four are all on one machine. A socket can also go across a network, which is why most programs that talk to a server use sockets. Shared memory is the fastest because after the setup no system call is needed to move data, but the processes must then take care not to disturb each other (Level 4). A pipe is the simplest and the most used.
This gives a way to choose. If the data is a stream going one way between a parent and a child, use a pipe. If they are unrelated, use a named pipe or a socket. If the data is big and needs speed, use shared memory. If only a notice is needed, a signal is enough.
Interview angle
Answer in your head first, then open it.
How does ls | wc work?
The shell creates a pipe, forks twice, connects the first child's output and the second child's input to the pipe with dup2, and runs both programs.
What happens when a pipe is full?
The writer waits until a reader makes room.
What is SIGPIPE?
The signal sent to a process that writes to a pipe with no reader.
How do two unrelated processes communicate on one machine?
A named pipe, a socket, shared memory or files.
Why close pipe ends?
So that the reader sees end of file and so that unused descriptors do not leak.
Check yourself: 1. Which channel can carry a number but no data? 2. Which channel works across a network? 3. Why is shared memory the fastest?
Words you will meet
| Word | Meaning |
|---|---|
| Pipe | A one-way byte channel inside the kernel |
| Read end, write end | The two descriptors of a pipe |
| End of file | A read that returns 0 |
| Pipeline | Several programs joined by pipes |
| FIFO | A pipe that has a name in the file system |
SIGPIPE |
The signal for writing to a pipe with no reader |
Quick notes
- A pipe is a one-way byte channel inside the kernel, created by
pipe, with a read end and a write end, each a file descriptor. - A named pipe, or FIFO, is a pipe that has a name in the file system, created with
mkfifo, so that processes that are not related byforkcan open it by name and use it like an ordinary pipe.