Mkfifo: how it works (en)
mkfifo stands for make first-in-first-out. It is a command in Unix-based operating systems like Ubuntu that is used to create a *named pipe*. A pipe is an inter-process communication mechanism that allows one process to write data into the pipe while another process reads that data.
Difference between `mkfifo` and a regular pipe:
- Regular pipe: Created dynamically when two processes communicate and disappears once the communication ends.
- Named pipe: Permanently created in the file system, allowing different processes to access it at any time as long as the pipe exists.
Why Use `mkfifo`?
- Inter-process communication: Ideal for connecting two or more independently running programs.
- Synchronization: Can be used to synchronize activities between processes.
- Gradual data processing: Data can be written and read incrementally, allowing for more efficient data processing.
How to Use `mkfifo`
Creating a named pipe:
mkfifo pipe_name
Example:
mkfifo mypipe
The above command creates a named pipe called `mypipe` in the current directory.
Accessing a named pipe:
- Reading from the named pipe:
cat < pipe_name
- Writing to the named pipe:
echo "Hello" > pipe_name
Usage Example:
Suppose we have two scripts:
- Script 1 (writer):
#!/bin/bash while true; do echo "Data from script 1" > mypipe sleep 1 done
- Script 2 (reader):
#!/bin/bash while true; do read line < mypipe echo "Received data: $line" done
Script 1 will continuously write data to `mypipe` every second, while script 2 will continuously read data from `mypipe` and display it on the screen.
Additional `mkfifo` Options
- `-m mode`: Set the access permissions for the named pipe.
- `-Z context`: Set the SELinux security context for the named pipe.
Real-World Use Cases
- Transferring data between two programs: For example, redirecting output from one program to the input of another.
- Implementing a simple queue: Data written to the named pipe will be processed sequentially by the reading process.
- Communication between parent and child processes: The child process can read commands from the parent process through a named pipe.
Conclusion
mkfifo is a highly useful tool for building more complex and efficient systems on Ubuntu Server. By understanding how it works, you can leverage it for various purposes, from inter-process communication to implementing synchronization mechanisms.