Sub topic 1
Why processes communicate: shared memory versus message passing
Prerequisites
This chapter assumes you already know the following:
- A process is a program in execution with its own address space. A thread is a unit of execution inside a process, and threads of one process share that process's address space.
- Process states (new, ready, running, waiting, terminated) and what a context switch does.
- The role of the CPU scheduler and what preemption means.
- How to read simple C-like pseudocode, including
fork()and system calls such asreadandwrite.
If any of these are unfamiliar, review them first. The rest of the tutorial builds on this chapter.
Why processes need to communicate
The operating system isolates processes on purpose. Each process gets its own virtual address space, so one process cannot read or overwrite another's variables. This protects the system from bugs and attacks. It also means that two processes cannot cooperate by simply touching the same variable.
Processes still need to cooperate. An independent process neither affects nor is affected by other processes. A cooperating process can affect or be affected by others. The usual reasons for cooperation are:
- Information sharing: several users or programs need the same data, such as a shared file or a database.
- Computation speed-up: a task is split into subtasks that run in parallel on several cores.
- Modularity: a system is split into separate processes, such as a web server, a database and a logger.
- Convenience: one user runs an editor, a compiler and a music player at the same time, and they exchange data.
Inter-process communication (IPC) is the set of mechanisms the operating system provides so that cooperating processes can exchange data and coordinate their actions. IPC comes in two basic models.
The two IPC models
In the shared-memory model, the processes agree on a region of memory that both can read and write. In the message-passing model, the processes exchange data by sending and receiving messages through the kernel.
Comparison
| Property | Shared memory | Message passing |
|---|---|---|
| Kernel involvement | Only to set up the region | On every send and receive |
| Speed for large data | Fast: no copying after setup | Slower: data is copied through the kernel |
| Synchronisation | Programmer must provide it | Largely built in, because receive can block until data arrives |
| Programming effort | Higher: races are easy to create | Lower for small data |
| Works across machines | No (same machine only) | Yes, with sockets |
| Best for | Large data, many accesses | Small messages, distributed systems |
The central trade-off for GATE questions is this. Shared memory is faster, but the programmer carries the burden of synchronisation. Message passing is slower for each transfer, but it is easier to get right and extends naturally to a network.
Communicating through shared memory
With shared memory, one process asks the kernel to create a region. Other processes then attach it to their own address spaces. After that, ordinary loads and stores reach the data, with no system call per access. The kernel is involved only at setup and teardown.
On POSIX systems, the calls are shmget, shmat, shmdt and shmctl (System V style), or shm_open and mmap (POSIX style). Threads of one process are a special case: they share the whole address space already, so global variables and the heap are shared with no setup.
The kernel does not coordinate the access. If two processes write the same location at the same time, the final value depends on timing. The next chapter explores this problem, called a race condition, in detail. Shared memory therefore always needs a synchronisation mechanism on top, which is the main subject of this tutorial.
A classic use of shared memory is the producer-consumer problem. A producer process fills a buffer and a consumer process empties it. The buffer lives in shared memory. Two kinds of buffer appear in textbooks:
- Unbounded buffer: no limit on size. The consumer may have to wait for items, but the producer never waits.
- Bounded buffer: a fixed size N. The producer must wait when the buffer is full, and the consumer must wait when it is empty.
A circular bounded buffer with in and out indices can hold at most N-1 items if only these two indices are used to tell full from empty. This is a common GATE detail. A buffer is empty when in == out and full when (in + 1) % N == out. Holding N items needs an extra counter, and that counter is itself a shared variable that creates a race.
Message passing
Message passing needs two operations: send(message) and receive(message). The processes need a communication link between them. The link can be implemented in different ways, and the design choices below are the ones usually examined.
Naming: direct and indirect communication
- Direct communication: each process names the other explicitly, as in
send(P, msg)andreceive(Q, msg). A link exists between exactly one pair of processes. - Indirect communication: messages go to and from mailboxes (also called ports). Processes communicate by sending to and receiving from a shared mailbox. Several processes may share a mailbox, so one link can serve many processes.
Synchronisation: blocking and non-blocking
| Operation | Blocking (synchronous) | Non-blocking (asynchronous) |
|---|---|---|
| Send | Sender waits until the message is received | Sender sends and continues at once |
| Receive | Receiver waits until a message is available | Receiver gets a message, or null if none is there |
When both send and receive are blocking, the arrangement is called a rendezvous.
Buffering
The link holds messages in a queue. Its capacity decides the behaviour:
- Zero capacity: no queue. The sender must block until the receiver takes the message.
- Bounded capacity: the queue has a fixed length. The sender blocks only when it is full.
- Unbounded capacity: the sender never blocks.
Common message-passing mechanisms
| Mechanism | Direction | Relationship between processes | Persists after the processes exit? |
|---|---|---|---|
| Anonymous pipe | One-way | Related, such as parent and child | No |
| Named pipe (FIFO) | One-way | Unrelated processes, found by a file system name | The name persists, the data does not |
| Message queue | Messages with types or priorities | Unrelated processes on one machine | Until removed (System V) or until reboot or unlink (POSIX) |
| Socket | Two-way | Same machine or across a network | No |
A pipe is a kernel buffer with a read end and a write end. Data is read in the order it was written (first in, first out). A read on an empty pipe blocks, and a write on a full pipe blocks. That blocking behaviour is a built-in synchronisation. A read returns end-of-file (0 bytes) only when every write end has been closed.
The following program sends five bytes from a parent to its child through an anonymous pipe.
#include <stdio.h>
#include <unistd.h>
int main(void) {
int fd[2];
char buf[6] = {0};
if (pipe(fd) == -1) return 1;
if (fork() == 0) {
close(fd[1]);
read(fd[0], buf, 5);
printf("child got: %s\n", buf);
close(fd[0]);
} else {
close(fd[0]);
write(fd[1], "hello", 5);
close(fd[1]);
}
return 0;
}pipe(fd) fills fd[0] with the read end and fd[1] with the write end. After fork(), both processes hold both ends. Each process closes the end it does not use. The child prints child got: hello.
Closing unused ends matters. If the child kept fd[1] open, a reader waiting for end-of-file would wait forever, because a write end would still exist. This is a frequent source of hangs.
A FIFO is created with mkfifo and behaves like a pipe, but it has a name in the file system. Unrelated processes can open it by that name. An open for reading normally blocks until another process opens it for writing.
A message queue is a kernel-held list of discrete messages. Unlike a pipe, which is a byte stream with no message boundaries, a queue preserves each message as a unit. Receivers can often pick messages by type or priority.
A socket is an endpoint for two-way communication. UNIX-domain sockets work between processes on one machine. Internet sockets, identified by an IP address and a port number, work across networks. Sockets are the only mechanism in this list that is designed for communication between different machines.
Choosing a model
Decision criteria that appear in exam questions:
- Large amounts of data exchanged on one machine: shared memory, because there is no copying through the kernel after setup.
- Small, infrequent messages, or a need for simple correct code: message passing.
- Processes on different machines: message passing with sockets.
- Many-core systems: message passing can scale better, because it avoids contention for shared locations and cache lines.
Shared memory can be slower than expected on multicore hardware for a different reason. When cores write the same cache lines, the cache-coherence protocol moves the lines back and forth between cores, and this adds delay.
Common errors
- Forgetting to close unused pipe ends, which makes a reader wait forever for end-of-file.
- Assuming a pipe is two-way. A standard pipe is one-way, so two-way exchange needs two pipes.
- Treating shared memory as safe because the kernel set it up. The kernel only maps the region.
- Confusing a blocking send with a rendezvous. A rendezvous needs both send and receive to be blocking.
- Forgetting that a circular buffer using only
inandoutholds N-1 items.
Summary
Processes are isolated, so cooperating processes need IPC. Shared memory is fast, because the kernel is involved only at setup, but it leaves synchronisation to the programmer. Message passing goes through the kernel on every transfer, which is slower, but its blocking semantics give some synchronisation for free, and it extends to networks. Pipes, FIFOs, message queues and sockets are the standard message-passing mechanisms. The cost of shared memory, which is the need to prevent unsafe concurrent access, is the problem the next chapters address, starting with race conditions.
Exercise
A parent and child share an anonymous pipe. The parent writes 10 bytes and closes its write end. The child has also forgotten to close its own copy of the write end, and it loops calling read until it gets 0 bytes. What happens after the child has read the 10 bytes, and why?
Show answer
The child's next read blocks forever. A read returns 0 (end-of-file) only when all write ends of the pipe are closed. The child still holds an open write end, so the kernel treats the pipe as possibly receiving more data. The fix is for the child to close its write end right after fork().
Exercise
A circular bounded buffer of size N = 8 uses only the indices in and out, with the empty test in == out. What is the maximum number of items it can hold, and what is the full test?
Show answer
It can hold at most 7 items (N-1). The full test is (in + 1) % 8 == out. If all 8 slots could be filled, in would equal out, which is the same condition as empty, so the two states could not be told apart.
Exercise
Name the IPC model and mechanism best suited to each case: (a) two processes on one machine that exchange a 500 MB image repeatedly, (b) a client on one host that talks to a server on another host, (c) a parent that sends a short command to its child.
Show answer
(a) Shared memory, because there is no per-transfer copying through the kernel, though the processes must synchronise access. (b) Message passing with sockets, since only sockets work across machines. (c) Message passing with an anonymous pipe, because the processes are related and the data is small.