Course contentsShow
← C
Lesson 1107 of 1,21915. Systems ProgrammingFree lesson

Creating FIFOs with mkfifo()

Creating FIFOs with mkfifo()

What you'll learn: How to create "Named Pipes" that allow two unrelated programs to talk to each other through the file system.

The problem with ordinary pipes

So far, you’ve likely used pipe(). While useful, it has a major limitation: it only works between a parent process and its children. Because the pipe exists only in memory, processes must share a memory space to "see" the pipe's file descriptors. If you have two completely separate programs—like a data logger and a visualizer—they can't use a standard pipe to communicate.

Enter the FIFO

A FIFO (First-In, First-Out) is often called a Named Pipe. Think of it like a physical mailbox attached to a house. Unlike a private conversation between a parent and child, a mailbox has a specific address (a filename). Any process that knows the address can drop off a letter or pick one up.

Even though a FIFO looks like a file on your hard drive, it doesn't actually store data on the disk. It acts as a temporary buffer in the kernel. If you write to it, the data stays in the "pipe" until another process reads it.

Using mkfifo()

To create this "mailbox," we use the mkfifo() function. It requires two arguments: the path where the pipe should live and the file permissions (similar to chmod).

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>

int main() {
    char *myfifo = "/tmp/my_messenger";

    // Create the named pipe
    // 0666 gives read/write permissions to everyone
    if (mkfifo(myfifo, 0666) == -1) {
        perror("mkfifo");
        return 1;
    }

    printf("FIFO created at %s\n", myfifo);
    return 0;
}

How it behaves

Once you run this code, you will see a new file at /tmp/my_messenger. If you run ls -l, you'll notice the file type starts with a p (for pipe).

The most important thing to remember is that FIFOs are blocking. If you try to open a FIFO to read from it, your program will "pause" and wait until another process opens it to write. They are like a two-person handshake; the connection isn't complete until both sides are ready.

Key takeaway

mkfifo() creates a special file on the system that acts as a permanent gateway for unrelated processes to exchange data streams.