Piping data between parent and child
What you'll learn: How to use the pipe() system call to create a one-way communication channel between a parent process and its child.
The "Tin Can Telephone" analogy
Imagine two people standing in different rooms who want to talk. You give them two tin cans connected by a string. One person holds the "mouthpiece" can, and the other holds the "earpiece" can. Information flows in only one direction through the string.
In C, a pipe is that string. When a process calls fork(), it creates a carbon copy of itself. If you create a pipe before you fork, both the parent and the child inherit access to that same pipe. This allows them to pass data across process boundaries.
Setting up the pipe
A pipe uses an array of two integers to represent file descriptors:
fd[0]is the read end (the earpiece).fd[1]is the write end (the mouthpiece).
For the pipe to work cleanly, you must decide who is talking and who is listening. If the parent is talking to the child, the parent closes its read end, and the child closes its write end. This prevents "feedback" and ensures the operating system knows when the message is finished.
Example: Sending a message to the child
Here is how you set up a simple one-way channel:
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main() {
int fd[2];
pid_t pid;
char buffer[20];
// 1. Create the pipe before forking
if (pipe(fd) == -1) return 1;
pid = fork();
if (pid > 0) {
// PARENT: The Sender
close(fd[0]); // Close unused read end
char *msg = "Hello, Child!";
write(fd[1], msg, strlen(msg) + 1);
close(fd[1]); // Done writing
} else {
// CHILD: The Receiver
close(fd[1]); // Close unused write end
read(fd[0], buffer, sizeof(buffer));
printf("Child received: %s\n", buffer);
close(fd[0]); // Done reading
}
return 0;
}
Why close the ends?
In systems programming, "housekeeping" is vital. If the child doesn't close the write end, its read() call might hang forever, waiting for more data that will never come. By closing the unused ends, you define a clear start and finish to the conversation, allowing read() to return 0 (EOF) once the sender is finished.
Key takeaway
A pipe is a unidirectional data channel created before a fork(), where one process writes to fd[1] and the other reads from fd[0].