Sub topic 3
Message passing: pipes, FIFOs, message queues and sockets
This chapter assumes you know what a process is and how the kernel switches between processes. It also assumes you can read C-like code and know that system calls such as read and write trap into the kernel. Shared memory, covered in the previous chapter, lets processes touch the same bytes. Message passing is the other IPC model. The kernel carries data from one process to another, and the processes never share an address space.
The working model
In message passing, a sender calls something like send or write. The kernel copies the data into a kernel-owned buffer. A receiver later calls receive or read, and the kernel copies the data out. The kernel buffer is the only place the two processes meet.
This has two consequences that matter for GATE questions.
- Synchronisation comes built in. A
readon an empty buffer blocks the receiver. Awriteto a full buffer blocks the sender. The kernel buffer therefore behaves like the bounded buffer in the producer-consumer problem, and the kernel does the semaphore work for you. - Every transfer costs copies and system calls. Shared memory needs the kernel only for setup. Message passing needs it on every message. This is why message passing is slower for large data but simpler and safer.
Textbooks classify message-passing designs along three axes.
| Axis | Options |
|---|---|
| Naming | Direct (the sender names the receiving process) or indirect (messages go to a mailbox or port) |
| Blocking | Blocking (synchronous) or non-blocking (asynchronous) send and receive |
| Buffer capacity | Zero (sender waits for receiver, called a rendezvous), bounded, or unbounded |
A blocking send plus a blocking receive gives a rendezvous. Real systems use bounded buffers, because unbounded memory does not exist.
Anonymous pipes
A pipe is a unidirectional byte stream held in a kernel buffer. pipe(fd) fills fd[0] with the read end and fd[1] with the write end. A pipe has no name, so two processes can share it only by inheriting the file descriptors. In practice that means fork.
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main(void) {
int fd[2];
char buf[6] = {0};
if (pipe(fd) == -1) return 1;
if (fork() == 0) {
close(fd[1]); /* child only reads */
read(fd[0], buf, 5);
printf("child got: %s\n", buf);
close(fd[0]);
} else {
close(fd[0]); /* parent only writes */
write(fd[1], "hello", 5);
close(fd[1]);
wait(NULL); /* let the child print first */
}
return 0;
}The blocking rules decide most pipe questions:
readon an empty pipe blocks while at least one write end is still open.readreturns 0 (end of file) only when every write end is closed and the buffer is empty.writeto a full pipe blocks. The Linux default capacity is 64 KiB.writeto a pipe with no open read end raisesSIGPIPE, which kills the process by default.- Writes of at most
PIPE_BUFbytes (4096 on Linux, at least 512 by POSIX) are atomic. They are never interleaved with another process's write.
Rule 2 explains the most common pipe bug. If the parent forgets close(fd[1]) and the child loops reading until it gets 0, the child hangs forever. The child's own copy of the write end keeps the pipe open.
The shell's ls | wc -l uses exactly this mechanism. The shell creates a pipe, forks twice, and redirects standard output of the first process and standard input of the second onto the pipe ends.
FIFOs (named pipes)
A FIFO behaves like a pipe but has a name in the file system, so unrelated processes can open it. You create it with mkfifo.
mkfifo /tmp/demo.fifo
cat /tmp/demo.fifo & # reader blocks until a writer opens
echo "hello" > /tmp/demo.fifo # writer; reader prints hello
rm /tmp/demo.fifoOpening a FIFO for reading blocks until some process opens it for writing, and the reverse also holds. This rendezvous at open time surprises many learners. A FIFO is still a one-way byte stream. For two-way traffic you need two FIFOs. The data lives in the kernel, not on disk. Only the name persists in the file system.
Message queues
A message queue stores discrete messages, not a byte stream. Each message has a length, and in POSIX queues it also has a priority. A receiver gets exactly one whole message per call, with boundaries preserved. In POSIX queues mq_receive returns the oldest message of the highest priority. System V queues use msgget, msgsnd and msgrcv, where the receiver can select messages by type.
Key properties:
- Any process that knows the queue name or key can send and receive. The processes need not be related or even running at the same time.
- The queue persists in the kernel until someone removes it (
mq_unlinkormsgctlwithIPC_RMID) or the system reboots. - A queue has a maximum number of messages and a maximum message size. A send to a full queue blocks, or fails with
EAGAINif the queue was opened non-blocking.
Sockets
A socket is a communication endpoint created with socket(). Sockets differ from the other mechanisms in two ways. They are bidirectional, and they work across machines.
- Stream sockets (TCP) give a reliable, ordered byte stream. Like a pipe, TCP has no message boundaries. Two 100-byte sends may arrive as one 200-byte read.
- Datagram sockets (UDP) preserve message boundaries but may lose, duplicate or reorder datagrams.
- UNIX-domain sockets work only on one machine, skip the network stack, and are the usual choice for local two-way IPC.
socketpair()creates a connected pair, much likepipe()but bidirectional.
Comparing the mechanisms
| Mechanism | Direction | Message boundaries | Who can communicate | Lifetime |
|---|---|---|---|---|
| Anonymous pipe | One-way | No (byte stream) | Related processes | Until all ends are closed |
| FIFO | One-way | No (byte stream) | Any local processes | Name persists; data does not |
| Message queue | Two-way via shared queue | Yes | Any local processes | Until removed or reboot |
| TCP socket | Two-way | No (byte stream) | Any host | Until connection closes |
| UDP socket | Two-way | Yes | Any host | Per datagram |
Common errors
- Unclosed pipe ends. Unused write ends keep the reader from ever seeing end of file. Unused read ends stop the writer from getting
SIGPIPE. - Assuming a read returns a whole message. On pipes, FIFOs and TCP,
readmay return fewer bytes than requested. Loop until you have the count you need, or add your own length prefix. - Using one pipe for both directions. Two processes both reading and writing the same pipe can consume their own data. Use two pipes or a socket pair.
- Ignoring return values.
readandwritecan return short counts or-1withEINTR. - Expecting a lock to be needed. Do not add a mutex around a pipe write for atomicity of small messages. The kernel already provides it up to
PIPE_BUF. Larger writes from several writers can interleave.
Exercise
A parent creates a pipe, forks a child, and writes 10 bytes to the pipe. The child runs while (read(fd[0], buf, 1) > 0) count++;. Neither process closes any pipe end, and the parent then calls wait() for the child. How many bytes does the child count, and what happens next?
Show answer
The child counts 10 and then blocks forever. Once the buffer is empty, read returns 0 only if every write end is closed. Both the parent's and the child's copies of fd[1] are still open, so read blocks. The parent is stuck in wait() waiting for the child, so the program deadlocks. The fix is for the child to close fd[1] and for the parent to close fd[1] after writing.