Introduction to named pipes (FIFOs)
What you'll learn: You will learn how to use named pipes to allow two completely independent programs to talk to each other using a special file on your hard drive.
The problem with ordinary pipes
Until now, you have likely used "anonymous" pipes (created with pipe()). These are great, but they have a major limitation: they only work between a parent process and its child. Because the pipe has no name and exists only in memory, a process cannot "find" a pipe created by a stranger.
Enter the FIFO (Named Pipe)
A FIFO (First-In, First-Out) is a "named" pipe. Think of it like a physical mail slot in a door. Unlike a secret handshake between a parent and child, a mail slot has a specific address. Any stranger can walk up to that address and drop a letter in, and the person inside can pick it up.
In Linux, a FIFO is a special type of file. You can actually see it in your file explorer, but it doesn't store data on the disk like a text file. Instead, it acts as a temporary gateway. When one program writes to it, the data stays in a buffer until another program reads it.
How to create one in C
You create a named pipe using the mkfifo() function. Once created, you interact with it just like a regular file using open(), read(), and write().
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main() {
char *myfifo = "/tmp/my_messenger";
// 1. Create the named pipe (the "mail slot")
// 0666 gives read/write permissions
mkfifo(myfifo, 0666);
printf("Waiting for a reader...\n");
// 2. Open the pipe for writing only
// This call "blocks" (waits) until someone opens it for reading!
int fd = open(myfifo, O_WRONLY);
// 3. Write data to the pipe
write(fd, "Hello from the other side!", 27);
// 4. Clean up
close(fd);
return 0;
}
The "Blocking" Behavior
One quirky thing about named pipes is that they are polite. If you open a FIFO to write, the open() function will pause your program until another program opens that same file to read. This ensures that no one is shouting into a void where no one is listening.
Key takeaway
Named pipes (FIFOs) allow unrelated processes to communicate by using a persistent filename as a shared meeting point.