Sub topic 7
Interprocess Communication: Pipes, Shared Memory, and Message Passing
This chapter assumes you know basic C, fork, pointers, and process life cycles. Interprocess communication (IPC) is how separate processes exchange data or coordinate their actions. Because processes usually have separate address spaces, one process cannot directly read another process's variables.
Why IPC Is Needed
A process may produce data that another process must consume. For example, a shell sends the output of one command to the input of another command. IPC provides both data transfer and synchronization.
| IPC method | Main idea | Typical strength |
|---|---|---|
| Pipe | A byte stream connects processes | Simple producer-consumer flow |
| Shared memory | Processes access a common memory region | Very fast for large data |
| Message passing | The kernel transfers separate messages | Clear boundaries and coordination |
Pipes
A pipe has a read end and a write end. Data written into the pipe is read in the same order. A pipe is commonly used between a parent and child because the child inherits the pipe's file descriptors after fork.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
int main(void) {
int fd[2];
if (pipe(fd) == -1) {
perror("pipe");
return 1;
}
pid_t pid = fork();
if (pid == -1) {
perror("fork");
return 1;
}
if (pid == 0) {
close(fd[1]);
char message[64];
ssize_t n = read(fd[0], message, sizeof(message) - 1);
if (n > 0) {
message[n] = '\0';
printf("child received: %s\n", message);
}
close(fd[0]);
_exit(0);
}
close(fd[0]);
const char *text = "data from parent";
write(fd[1], text, strlen(text));
close(fd[1]);
waitpid(pid, NULL, 0);
return 0;
}Closing unused ends matters. A reader detects end-of-file only after every write end has been closed. A pipe has limited capacity, so a writer can block when the buffer is full.
Shared Memory and Message Passing
Shared memory maps the same physical memory region into multiple processes. It avoids repeated kernel copying and is efficient for large data. However, simultaneous access can cause a race condition, so processes need synchronization such as semaphores or mutexes.
Message passing uses operations such as send and receive. The kernel manages the message queue and can preserve message boundaries. This design is often easier to reason about, but transferring data may require more kernel work.
Exam Method
For an IPC question, identify the direction of data flow, whether communication is local or across a network, and whether synchronization is required. Remember that shared memory improves transfer speed but does not automatically make access safe.
Exercise
Why can shared memory still produce incorrect results when two processes update the same counter?
Show answer
The updates can interleave. Each process may read the same old value and then overwrite the other process's update. A synchronization mechanism is required.