In Linux, pipes are a fundamental mechanism for inter-process communication (IPC), enabling data to flow directly from one process to another. A pipe connects the standard output of one process to the standard input of another, allowing users and developers to build powerful and flexible workflows. Most Linux users are familiar with pipes through the shell’s |
operator, commonly used to link commands like ls | sort
. However, beyond basic shell usage, Linux also provides low-level system calls that allow programmers to create and control pipes programmatically for more sophisticated communication between processes.
Pipes operate on a First-In-First-Out (FIFO) principle, ensuring that the data written first is also read first. The pipe()
system call is used to create a pair of connected file descriptors, one for reading and one for writing. Typically, pipes are used between related processes, such as a parent and its child created through fork()
. Proper handling of these file descriptors, including closing unused ends, is essential to avoid resource leaks and ensure efficient communication.
Ex:cmd1 | cmd2
– ls | wc
– who | sort
– cat file.txt | sort | wc
The lower-level pipe function provides a means of passing data between two programs, without the overhead of invoking a shell to interpret the requested command. It also gives you more control over the reading and writing of data.
The pipe function has the following prototype:
#include
int pipe(int file_descriptor[2]);
#include<unistd,h>
size_t write(int fildes, const void *buf, size_t nbytes);
#include
size_t read(int fildes, void *buf, size_t nbytes);
Indian Institute of Embedded Systems – IIES