In Linux, inter-process communication (IPC) is vital for allowing different processes to exchange data and coordinate tasks. One of the simplest and most effective IPC mechanisms is the FIFO (First In, First Out), also known as a named pipe. Unlike regular pipes that can only be used between related processes, FIFOs allow communication between unrelated processes, making them highly flexible in complex applications.
A FIFO provides a file-based communication method where data written first is read first, ensuring orderly transmission. It can be created either through simple command-line tools like mkfifo
and mknod
, or programmatically in C using system calls. In this guide, we’ll explore how to create, open, read from, and write to FIFOs both manually and in C programming, offering a step-by-step approach to building efficient communication between processes in Linux.
Whether you’re a system programmer, a Linux enthusiast, or someone curious about IPC mechanisms, understanding FIFOs will deepen your grasp of Linux internals and enhance your programming skills.
#include<sys/types.h>
#include<sys/stat.h>
int mkfifo(const char *filename, mode_t mode);
int mknod(const char *filename, mode_t mode | S_IFIFO, (dev_t) 0);
Like the mknod and mkfifo command, you can use the mknod function for making many special types of files. Using a dev_t value of 0 and ORing the file access mode with S_IFIFO is the only portable use of this function that creates a named pipe.
Unlike unnamed Pipe, FIFO needs to be opened for reading and writing so the file descriptors can be used along with it.
fd = open(const char *path, O_RDONLY);
fd = open(const char *path, O_WRONLY);
#include
size_t write(int fildes, const void *buf, size_t nbytes);
It arranges for the first nbytes bytes from buf to be written to the file associated with the file descriptor fildes.
It returns the number of bytes actually written. This may be less than nbytes if there has been an error in the file descriptor. If the function returns 0, it means no data was written; if it returns –1, there has been an error in the write call.
#include
size_t read(int fildes, void *buf, size_t nbytes);
It reads up to nbytes bytes of data from the file associated with the file descriptor fildes and places them in the data area buf.
It returns the number of data bytes actually read, which may be less than the number requested. If a read call returns 0, it had nothing to read; it reached the end of the file. Again, an error on the call will cause it to return –1.
Indian Institute of Embedded Systems – IIES