The mkfifo
command in Linux is used to create named pipes, also known as FIFOs (First In, First Out). FIFOs are special types of files that allow two processes to communicate with each other by reading and writing data in a synchronized manner. In this tutorial, we will cover how to use the mkfifo
command with practical examples. Whether you are setting up a server locally or using a Windows VPS UK, this guide will help you understand how to use FIFOs effectively.
1. Syntax of the mkfifo Command
The basic syntax of the mkfifo
command is:
mkfifo [OPTION] NAME
Here, NAME
represents the name of the FIFO file you want to create.
2. Example 1: Create a Simple FIFO File
To create a FIFO file named my_fifo
, you can use the following command:
mkfifo my_fifo
This creates a named pipe that can be used by two processes to communicate. You can confirm the file type by running:
ls -l my_fifo
You will see the file listed with a p
at the beginning, indicating that it is a FIFO.
3. Example 2: Write Data to the FIFO
You can write data into the FIFO using the echo
command. Open one terminal and run:
echo "Hello from FIFO" > my_fifo
This will write the message "Hello from FIFO" to the FIFO file. The command will hang until the data is read.
4. Example 3: Read Data from the FIFO
To read the data from the FIFO, open another terminal and use the cat
command:
cat < my_fifo
This will display the message "Hello from FIFO" in the second terminal, completing the communication between the two processes.
5. Example 4: Set Permissions for the FIFO
You can set specific permissions when creating a FIFO file using the -m
option. For example, to create a FIFO file with read and write permissions for all users, run:
mkfifo -m 666 public_fifo
This will create a FIFO named public_fifo
with read and write access for all users.
6. Example 5: Remove a FIFO File
If you no longer need the FIFO file, you can remove it using the rm
command:
rm my_fifo
This will delete the FIFO file from your system.