Sub topic 7
Interprocess Communication: Pipes, Shared Memory, Message Passing
This chapter assumes you know fork, exec and waitpid from the previous chapter, and that you can read basic C. It covers why processes need to communicate, the two basic IPC models, and how pipes work, since GATE asks about them most often.
Why processes need IPC
Each process has its own address space, so one process cannot read or write another's variables. This isolation protects processes from each other. It also means that cooperating processes, such as a shell pipeline or a web server with worker processes, need a channel the kernel provides. That channel is called interprocess communication (IPC).
There are two fundamental models:
- Shared memory. The kernel maps one region of physical memory into the address spaces of two or more processes. After setup, they communicate by ordinary loads and stores.
- Message passing. Processes exchange discrete messages through kernel-managed operations, usually
send(destination, message)andreceive(source, message). Every exchange is a system call.
Comparing the two models
| Property | Shared memory | Message passing |
|---|---|---|
| Kernel involvement | Only to create and map the region | Every send and receive |
| Speed for large data | Fast, with no copy through the kernel | Slower, since data is copied in and out |
| Synchronization | Programmer's job (semaphores, mutexes) | Largely built in, because receive can block |
| Works across machines | No | Yes (sockets, RPC) |
| Typical use | Large data on one machine | Small messages, distributed systems |
Message passing is easier to get right, and shared memory is faster for bulk data. Neither is always better, and GATE questions usually ask you to match a property to a model.
Pipes
A pipe is a unidirectional byte stream held in a kernel buffer. pipe(int fd[2]) creates it and returns two file descriptors:
fd[0]is the read end.fd[1]is the write end.
A pipe has no name, so two processes can share it only by inheritance. The usual pattern is to call pipe first, then fork. The child inherits both descriptors.
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
int main(void) {
int fd[2];
if (pipe(fd) < 0) {
perror("pipe");
return 1;
}
pid_t pid = fork();
if (pid < 0) {
perror("fork");
return 1;
}
if (pid == 0) {
close(fd[1]); /* child only reads */
char buf[64];
ssize_t n = read(fd[0], buf, sizeof buf - 1);
if (n < 0) {
perror("read");
_exit(1);
}
buf[n] = '\0';
printf("child read: %s\n", buf);
fflush(stdout); /* _exit does not flush stdio */
close(fd[0]);
_exit(0);
}
close(fd[0]); /* parent only writes */
const char *msg = "ping";
write(fd[1], msg, strlen(msg));
close(fd[1]); /* signals end of data */
waitpid(pid, NULL, 0);
return 0;
}The program prints child read: ping. Each process closes the end it does not use, and this is not optional.
Pipe semantics that exams test
- Blocking read. If the pipe is empty and a write end is still open somewhere,
readblocks. - End of file. If the pipe is empty and every write end is closed,
readreturns 0. A reader loops until it sees 0. - Blocking write. If the buffer is full (64 KiB by default on Linux),
writeblocks until a reader drains it. - Broken pipe. If every read end is closed,
writeraisesSIGPIPEand fails withEPIPE. - Atomicity. Writes of at most
PIPE_BUFbytes (at least 512 by POSIX, 4096 on Linux) are not interleaved with other writers' data. - Order. Bytes come out in the order they went in (FIFO). A pipe is a byte stream with no message boundaries.
A shell command such as ls | wc -l uses the same mechanism. The shell calls pipe, forks twice, and uses dup2 to connect the first child's standard output to the write end and the second child's standard input to the read end.
Named pipes
An ordinary pipe lives only as long as the processes holding its descriptors, and only related processes can share it. A named pipe (FIFO) is created with mkfifo and has a name in the file system, so unrelated processes can open it. It is still a one-way byte stream.
Shared memory in practice
Related processes can share memory by mapping an anonymous shared region before fork:
#include <stdio.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void) {
int *value = mmap(NULL, sizeof(int), PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_ANONYMOUS, -1, 0);
if (value == MAP_FAILED) {
perror("mmap");
return 1;
}
*value = 0;
pid_t pid = fork();
if (pid < 0) {
perror("fork");
return 1;
}
if (pid == 0) {
*value = 42; /* visible to the parent */
_exit(0);
}
waitpid(pid, NULL, 0);
printf("value = %d\n", *value);
munmap(value, sizeof(int));
return 0;
}This prints value = 42. Compare it with a plain global variable: after fork, a child's write to a global changes only the child's copy. With MAP_SHARED both processes see the same physical page. Unrelated processes use POSIX shm_open plus mmap instead, which names the region.
The kernel gives no protection against races on shared memory. Here waitpid makes the parent read only after the child finishes. With two processes updating a counter at the same time, you would need a semaphore or mutex. This is the classic producer-consumer setting, where a bounded buffer lives in shared memory and the processes coordinate their access.
Message passing design choices
A message-passing facility is described by a few design decisions. Textbooks list them, and GATE-style questions can ask about them.
- Naming. With direct communication the sender names the receiver, as in
send(P, m). With indirect communication, messages go to a mailbox or port, and any process holding it can receive. - Synchronization. A blocking send waits until the message is received or accepted. A non-blocking send returns at once. A blocking receive waits for a message. A non-blocking receive returns a message or nothing. When both send and receive block, the arrangement is called a rendezvous.
- Buffering. A zero-capacity link holds no messages, so the sender must block. A bounded link holds a fixed number, and the sender blocks only when it is full. An unbounded link never blocks the sender.
Linux provides POSIX message queues (mq_open, mq_send, mq_receive). Sockets provide the same model across a network. Unlike pipes, message queues preserve message boundaries.
Choosing a mechanism
- Parent and child streaming bytes in one direction: a pipe.
- Unrelated processes streaming bytes on one machine: a FIFO or a socket.
- Large shared data structure on one machine: shared memory plus synchronization.
- Processes on different machines: sockets or RPC, which are message passing.
Exercise
A parent calls pipe(fd) and then fork(). The parent writes 10 bytes to fd[1] and calls waitpid. The child loops on read(fd[0], ...) until it returns 0. Neither process closes any descriptor. What happens, and what fixes it?
Show answer
The program hangs. The child reads the 10 bytes, then blocks on the next read, because a write end (fd[1]) is still open in both the parent and the child. read can return 0 only when every write end is closed. The parent also sits in waitpid, so neither process can proceed (a deadlock). The fix is for the child to close fd[1] right after fork, and for the parent to close fd[1] after writing, before waitpid.
Exercise
State two reasons why shared memory is usually faster than message passing for large data on one machine, and one thing it makes harder.
Show answer
First, the kernel is involved only when the region is set up, so later accesses are ordinary memory operations and not system calls. Second, the data is not copied between user space and kernel buffers on each exchange. It is harder because the processes must synchronize their accesses themselves (for example with semaphores) to avoid race conditions.