[Day 3] 3. Pipes
Pipes in Linux
Pipes are used for Inter-Process Communication (IPC), allowing data to flow between processes. They have two ends: one for reading and one for writing.
Types of Pipes:
-
Unnamed Pipes:
- Used for communication between related processes (like a parent and child process).
- Automatically created by the operating system.
-
Named Pipes (FIFOs):
- Created using the command.
mkfifo - Can be used for communication between unrelated processes.
- Created using the
Creating a Named Pipe:
-
Command:
mkfifo fifo- This command creates a named pipe called . It follows the First In, First Out (FIFO) principle, meaning data written first will be read first.
fifo
- This command creates a named pipe called
How Pipes Work Internally:
-
Buffer:
-
A circular buffer is created in memory, functioning like an array.
-
For example:
!3. Pipes 2.png
-
The buffer is assigned file descriptors:
- : Read end of the pipe
arr[0] - : Write end of the pipe
arr[1]
-
-
File Descriptors:
-
When a pipe is created using the
system call, two file descriptors are generated:pipe()- : Represents the read end of the pipe (associated with
arr[0]).stdin - : Represents the write end of the pipe (associated with
arr[1]).stdout
-
The default standard input (
) and standard output (stdin) are replaced with the pipe's read and write ends.stdout
-
Synchronisation and Blocking Behaviour:
-
Blocking Behaviour:
- If a read operation is attempted on an empty pipe, the reading process is blocked and goes into a waiting state until data is written.
- If the buffer is full, the writing process is automatically blocked until space is available in the buffer.
-
Unidirectional Communication:
- Pipes allow for unidirectional data flow (data can only flow in one direction—from the writer to the reader).
- Because two processes are typically related, unnamed pipes are often used for simpler IPC tasks.
Example Workflow:
- Writing to the Pipe:
- A process writes data to the pipe using the write descriptor ().
arr[1]
- A process writes data to the pipe using the write descriptor (
- Reading from the Pipe:
- Another process reads the data from the pipe using the read descriptor ().
arr[0]
- Another process reads the data from the pipe using the read descriptor (
Diagram of Pipe Communication:
!7. Pipe.png
Conclusion:
Pipes are a fundamental IPC mechanism in Linux that facilitate communication between processes. By understanding the behaviour of pipes, including their blocking nature and unidirectional data flow, you can effectively manage data transfer in multi-process applications.
Read Next
[Day 3] 4. Some more commands
#### **1. Head and Tail Commands:** - **`head`**: Displays the first part of files. `head -5 filename.txt` - This command pr...
[Day 4] 1. Few more Commands
## **Types of Commands in Linux** #### **1. Internal Commands** - **Definition**: Commands implemented within the shell program itself. - **Exe...