Implementation of FIFO in Linux: Named Pipe with C Programming Examples

Implementation of FIFO in Linux Named Pipe with C Programming Examples

Inter-Process Communication (IPC) is an essential feature of Linux that allows multiple processes to exchange data and coordinate tasks efficiently. Among the various IPC mechanisms available, FIFO (First In, First Out), also known as a named pipe, offers a simple and reliable way for unrelated processes to communicate.

Unlike an unnamed pipe, which works only between processes with a common parent, a FIFO exists as a special file in the Linux file system. Any authorized process that knows the FIFO’s path can open it for reading or writing, making it useful for client-server applications, logging systems, shell scripting, embedded Linux development, and process synchronization.

Linux provides multiple ways to create a FIFO, including the mkfifo command, the mknod command, and the mkfifo() system call in C. Once created, processes exchange data using standard file operations such as open(), read(), and write(), making FIFO programming straightforward for beginners and experienced developers alike.

In this guide, you’ll learn what FIFO is, how it works, how to create it using Linux commands and C programming, and where it is used in real-world applications.

Implementation of FIFO in Linux involves creating a named pipe that enables communication between unrelated processes. A FIFO can be created using the mkfifo command or the mkfifo() system call, after which one process writes data while another reads it using standard Linux file operations like open(), read(), and write().

Table of Contents
Implementation of FIFO in Linux: Named Pipe with C Programming Examples

What is FIFO in Linux?

A FIFO (First In, First Out) is a special type of file used for Inter-Process Communication (IPC) in Linux. It behaves like a queue, where the first data written into the FIFO is the first data read by another process.

Unlike regular pipes, a FIFO is stored in the file system with a unique filename, allowing unrelated processes to communicate without sharing the same parent process.

FIFO Characteristics

  • Also known as a Named Pipe
  • Supports communication between unrelated processes
  • Maintains the order of data (First In, First Out)
  • Appears as a special file in the Linux file system
  • Uses standard file operations (open(), read(), write(), and close())
  • Remains available until it is explicitly deleted

Example

Suppose a logging application continuously writes system events to a FIFO. Another monitoring application reads those events in the exact order they were generated without directly interacting with the logging process.

registor_now_P

Why is FIFO Important in Linux?

Many Linux applications require processes to exchange information efficiently. FIFO provides a lightweight communication mechanism without the complexity of sockets or shared memory.

FIFO is commonly used because it:

  • Enables communication between unrelated processes
  • Simplifies data exchange through file-based communication
  • Preserves the sequence of transmitted data
  • Integrates easily with shell scripts and Linux commands
  • Requires minimal programming effort
  • Is supported by almost every Linux distribution

Common Use Cases

Application

How FIFO is Used

Shell scripting

Exchange data between scripts

Client-server programs

Pass requests and responses

Embedded Linux

Communication between user-space applications

Logging systems

Stream log messages

Process synchronization

Coordinate multiple processes

Industrial automation

Exchange status information between software modules

Features of FIFO in Linux

FIFO offers several features that make it suitable for Linux IPC.

1. Named Communication Channel

Unlike unnamed pipes, FIFO has a filename in the file system, making it accessible to different processes.

2. First In, First Out Data Order

Data is read in exactly the same order it was written.

Example:

Written:

A

B

C

Read:

A

B

C

3. Supports Unrelated Processes

Processes do not need to be created from the same parent.

For example:

  • Terminal 1 writes data.
  • Terminal 2 reads the same data.

4. File System-Based IPC

FIFO behaves like a file.

It can be viewed using:

ls -l

A FIFO file is displayed with the file type p, indicating a named pipe.

Example:

prw-r--r-- 1 user user 0 Jul 6 10:30 my_fifo

5. Standard File Operations

Linux treats FIFO similarly to a file, allowing developers to use familiar system calls.

Common functions include:

  • open()
  • read()
  • write()
  • close()
  • unlink()

6. Kernel Buffer Management

The Linux kernel temporarily stores data inside the FIFO until another process reads it, eliminating the need for developers to implement their own buffering mechanism.

How Does FIFO Work in Linux?

A FIFO acts as an intermediary communication channel between two or more processes. One process writes data into the FIFO, while another process reads it in the same order.

FIFO Communication Workflow

Writer Process

      │

      ▼

+------------------+

|      FIFO        |

| (Kernel Buffer)  |

+------------------+

      │

      ▼

Reader Process

Working Process

  1. Create a FIFO using the mkfifo command or the mkfifo() system call.
  2. The writer process opens the FIFO in write mode.
  3. The reader process opens the FIFO in read mode.
  4. Data written by the writer is stored temporarily in the kernel buffer.
  5. The reader retrieves the data in the same order it was written.
  6. Both processes close the FIFO after communication is complete.
  7. If no longer required, the FIFO file can be removed using the unlink() function or the rm command.

Blocking Behavior

FIFO operations are blocking by default.

  • If a reader opens the FIFO before any writer is available, it waits until a writer connects.
  • If a writer opens the FIFO before any reader is available, it also waits until a reader opens the FIFO.

This synchronization helps prevent data loss during communication.

FIFO Communication Example

Writer Process

Temperature = 28°C

Humidity = 65%

Pressure = 1013 hPa

↓ FIFO ↓ Reader Process

Temperature = 28°C

Humidity = 65%

Pressure = 1013 hPa

The reader receives the information in exactly the same sequence in which it was written, demonstrating the First In, First Out principle.

Creating FIFO Using Linux Commands

Linux provides built-in commands to create a FIFO without writing any C code. These commands are useful for testing named pipes and understanding how FIFO communication works before implementing it programmatically.

Method 1: Using the mkfifo Command

The mkfifo command is the simplest and most commonly used method to create a named pipe.

Syntax

mkfifo

Example

mkfifo my_fifo

After executing the command, a FIFO file named my_fifo is created in the current directory.

Verify the file using:

ls -l

Example output:

prw-r--r-- 1 user user 0 Jul 6 10:30 my_fifo

Here, the first character p indicates that the file is a named pipe (FIFO).

Method 2: Using the mknod Command

Another way to create a FIFO is with the mknod command.

Syntax

mknod p

Example

mknod my_fifo p

Although this command also creates a FIFO, mkfifo is generally preferred because it is specifically designed for creating named pipes and is easier to use.

Checking Whether the FIFO Exists

Use the following command to verify that the FIFO has been created successfully.

file my_fifo

Example output:

my_fifo: fifo (named pipe)

Removing a FIFO

Once communication is complete, the FIFO can be removed like any other file.

rm my_fifo

or

unlink my_fifo

Creating a FIFO Using C Programming

In C, a FIFO is created using the mkfifo() system call. This method is commonly used in Linux applications where the FIFO must be created dynamically during program execution.

Header Files

c

#include <sys/types.h>

#include <sys/stat.h>

Syntax

c

int mkfifo(const char *pathname, mode_t mode);

Parameters

Parameter

Description

pathname

Name or path of the FIFO

mode

Permission bits (for example, 0666)

Return Value

Return Value

Meaning

0

FIFO created successfully

-1

An error occurred

Example Program

c

#include

#include <sys/types.h>

#include <sys/stat.h>

int main()

{

   if(mkfifo("my_fifo",0666)==-1)

   {

       printf("FIFO already exists or cannot be created.\n");

   }

   else

   {

       printf("FIFO created successfully.\n");

   }

   return 0;

}

Output

FIFO created successfully.

Creating FIFO Using mknod()

Although rarely used for named pipes today, Linux also provides the mknod() function.

Syntax

c

int mknod(const char *pathname, mode_t mode, dev_t dev);

Example:

c

mknod(“my_fifo”, S_IFIFO | 0666, 0);

For portability and readability, mkfifo() is recommended over mknod() when creating named pipes.

Opening a FIFO

Before data can be exchanged, both communicating processes must open the FIFO.

Linux uses the open() system call to obtain a file descriptor for the FIFO.

Header File

c

#include

Open FIFO for Reading

c

int fd;

fd = open("my_fifo", O_RDONLY);

The process waits until another process opens the FIFO for writing.

Open FIFO for Writing

c

int fd;

fd = open("my_fifo", O_WRONLY);

The writer waits until a reader opens the FIFO.

Open FIFO for Reading and Writing

c

int fd;

fd = open("my_fifo", O_RDWR);

This mode allows the same process to read from and write to the FIFO, although it is less common in IPC applications.

File Descriptor

When open() succeeds, it returns a file descriptor, which is used by other system calls such as:

  • read()
  • write()
  • close()

Example:

c

int fd;

fd = open("my_fifo", O_RDONLY);

if(fd==-1)

{

   printf("Unable to open FIFO\n");

}

Explore Courses - Learn More

Reading and Writing Data Using FIFO

Once the FIFO is opened, data can be transferred using the standard Linux file operations.

The write() System Call

The writer process sends data into the FIFO using write().

Header File

c

#include

Syntax

c

ssize_t write(int fd, const void *buffer, size_t size);

Parameters

Parameter

Description

fd

File descriptor

buffer

Data to write

size

Number of bytes

Return Value

Value

Description

Positive

Number of bytes written

0

No data written

-1

Error

Example

c

char message[]="Hello Linux";

write(fd,message,sizeof(message));

The read() System Call

The reader retrieves data from the FIFO using read().

Syntax

c

ssize_t read(int fd, void *buffer, size_t size);

Parameters

Parameter

Description

fd

File descriptor

buffer

Memory to store data

size

Maximum bytes to read

Return Value

Value

Description

Positive

Bytes successfully read

0

End of file

-1

Error

Example

c

char buffer[100];

read(fd,buffer,sizeof(buffer));

printf("%s",buffer);

Complete FIFO Program Example

The following example demonstrates communication between two unrelated processes using a named pipe.

Writer Program

c

#include

#include

#include

int main()

{

   int fd;

   char message[]="Welcome to IIES";

   fd=open("my_fifo",O_WRONLY);

   write(fd,message,sizeof(message));

   close(fd);

   return 0;

}

Reader Program

c

#include

#include

#include

int main()

{

   int fd;

   char buffer[100];

   fd=open("my_fifo",O_RDONLY);

   read(fd,buffer,sizeof(buffer));

   printf("Received Message: %s\n",buffer);

   close(fd);

   return 0;

}

How to Compile the Programs

Compile both programs using the GCC compiler.

gcc writer.c -o writer

gcc reader.c -o reader

Running the FIFO Program

Step 1

Create the FIFO.

mkfifo my_fifo

Step 2

Open the first terminal and run the reader.

./reader

The reader waits until data becomes available.

Step 3

Open another terminal and execute the writer.

./writer

Expected Output

Writer Terminal

Data sent successfully.

Reader Terminal

Received Message: Welcome to IIES

The message is transferred through the named pipe without requiring the two processes to have a parent-child relationship.

Code Explanation

Step

Description

Create FIFO

A named pipe is created using mkfifo.

Open FIFO

The writer opens the FIFO in write mode, and the reader opens it in read mode.

Write Data

The writer sends the message using write().

Store Data

The Linux kernel temporarily stores the message in the FIFO buffer.

Read Data

The reader retrieves the message using read().

Close FIFO

Both processes release the file descriptor using close().

Steps to Implement FIFO Between Unrelated Processes

The following workflow summarizes the complete process of implementing FIFO communication in Linux.

Step

Description

1. Create FIFO

Create a named pipe using the mkfifo command or the mkfifo() system call.

2. Open FIFO

The writer opens the FIFO in write mode, while the reader opens it in read mode.

3. Write Data

The writer sends data to the FIFO using the write() system call.

4. Read Data

The reader retrieves the data using the read() system call.

5. Close FIFO

Both processes close the file descriptor using close().

6. Remove FIFO

Delete the FIFO using unlink() or the rm command when it is no longer needed.

FIFO Communication Workflow

Create FIFO

     │

     ▼

Open Reader Process

     │

     ▼

Open Writer Process

     │

     ▼

Write Data

     │

     ▼

Kernel FIFO Buffer

     │

     ▼

Read Data

     │

     ▼

Close FIFO

     │

     ▼

Delete FIFO (Optional)

Advantages of FIFO in Linux

FIFO is widely used because it provides a simple and reliable communication mechanism between processes.

  • Enables communication between unrelated processes.
  • Easy to create using Linux commands or C programming.
  • Maintains data in First In, First Out (FIFO) order.
  • Uses standard file operations like open(), read(), and write().
  • Requires minimal programming compared to sockets.
  • Appears as a file, making it easy to manage and debug.
  • Suitable for shell scripting and automation tasks.
  • Built into Linux and supported by POSIX-compliant systems.
  • Efficient for transferring small to medium-sized data.
  • Does not require shared memory management.

Limitations of FIFO in Linux

Although FIFO is simple to use, it has some limitations that developers should consider.

Limitation

Description

Half-duplex communication

Data flows in only one direction at a time. Two FIFOs are required for two-way communication.

Blocking behavior

A reader waits for a writer, and a writer waits for a reader unless non-blocking mode is used.

Local communication

FIFO works only between processes on the same machine.

Limited buffering

The kernel buffer size is fixed and may fill if data is not read promptly.

No message priority

FIFO preserves order but does not prioritize messages.

Not suitable for networking

Named pipes cannot communicate across different systems like sockets can.

Real-World Applications of FIFO

FIFO is commonly used in Linux-based systems where processes need a simple and efficient communication mechanism.

Application

Description

Embedded Linux Systems

Exchange data between user-space applications.

Industrial Automation

Share status and control information between software modules.

Logging Systems

Stream application logs to monitoring tools.

Shell Scripting

Pass data between scripts and background processes.

Client-Server Applications

Transfer requests and responses between local applications.

IoT Gateways

Exchange sensor data between software components.

Monitoring Tools

Deliver real-time system statistics.

Testing and Debugging

Simulate communication between multiple Linux processes.

Best Practices for FIFO Programming

Following these practices helps improve reliability and avoid common runtime issues.

  • Use mkfifo() instead of mknod() when creating named pipes programmatically.
  • Check the return values of open(), read(), write(), and close().
  • Handle errors using perror() or appropriate error messages.
  • Remove unused FIFOs using unlink() or rm.
  • Choose appropriate file permissions while creating the FIFO.
  • Close file descriptors after communication is complete.
  • Avoid writing data larger than the FIFO buffer unless the reader is actively consuming it.
  • Use non-blocking mode (O_NONBLOCK) when blocking behavior is not desirable.

Common Mistakes and How to Avoid Them

Common Mistake

Why It Happens

Solution

Opening the writer before the reader

The writer waits indefinitely for a reader.

Start the reader first or use non-blocking mode.

Ignoring return values

Errors remain undetected.

Always verify the return value of every system call.

Forgetting to close file descriptors

Resource leaks may occur.

Call close() after communication.

Not deleting unused FIFOs

Old FIFO files accumulate in the file system.

Remove them using unlink() or rm.

Using incorrect permissions

Other processes cannot access the FIFO.

Create the FIFO with appropriate permissions such as 0666.

Assuming FIFO supports network communication

FIFO only works on the local system.

Use sockets for communication between different machines.

Debugging FIFO Applications

When FIFO communication does not work as expected, Linux provides several useful tools for troubleshooting.

Verify the FIFO File

ls -l my_fifo

The file should begin with the letter p, indicating that it is a named pipe.

Check the File Type

file my_fifo

Expected output:

my_fifo: fifo (named pipe)

Trace System Calls

strace ./writer

or

strace ./reader

strace helps identify failures in open(), read(), write(), and other system calls.

Check Which Process Is Using the FIFO

lsof my_fifo

This command displays the processes currently accessing the FIFO.

FIFO vs Pipe: Comparison Table

Feature

FIFO (Named Pipe)

Pipe (Unnamed Pipe)

File name

Yes

No

Exists in file system

Yes

No

Communication

Unrelated processes

Parent-child processes

Persistence

Exists until deleted

Exists until processes terminate

Creation

mkfifo() or mkfifo command

pipe() system call

Accessibility

Any authorized process

Related processes only

Ease of debugging

Easy

Moderate

Conclusion

The implementation of FIFO in Linux provides a straightforward and efficient method for Inter-Process Communication (IPC) between unrelated processes. By creating a named pipe with the mkfifo command or the mkfifo() system call, applications can exchange data using familiar file operations such as open(), read(), and write().

FIFO is well suited for local communication in Linux, particularly in shell scripting, logging systems, embedded Linux applications, client-server programs, and industrial automation. Understanding its working principle, creation methods, advantages, limitations, and best practices will help you build reliable IPC solutions and strengthen your Linux system programming skills.

As you continue learning Linux programming, FIFO serves as an excellent foundation before exploring advanced IPC mechanisms such as message queues, shared memory, semaphores, and UNIX domain sockets.

Talk to Academic Advisor

FAQs

FIFO (First In, First Out) is a named pipe used for Inter-Process Communication (IPC). It enables unrelated processes to exchange data while preserving the order in which the data is written.

Unlike a regular pipe, a FIFO is stored in the Linux file system with a unique filename. Processes can access it using this name, which is why it is called a named pipe.

A FIFO can be created using the Linux command:

mkfifo my_fifo

or programmatically using the mkfifo() system call in C.

A pipe is an unnamed communication channel used between related processes, whereas a FIFO is a named communication channel that allows unrelated processes to exchange data.

Yes. Multiple processes can open the same FIFO for reading or writing. However, proper synchronization is required to prevent unexpected behavior when several processes access it simultaneously.