Named Pipe or FIFO with example C program


Introduction

Named pipes, also referred to as FIFOs (First In, First Out), constitute essential IPC systems in software systems. They offer a quick and effective method for successfully transferring information between processes. Specialized kinds of files known as named pipes serve as a means for interaction among unconnected procedures that operate on an identical structure as well as on separate ones.

First-in, first-out (FIFO) named pipes ensure that information composed to the line by a single procedure is read from the pipe by another course in the identical order. Therefore, They are particularly advantageous when processes must communicate independently without sharing storage or direct dependency management.

In this article, we will be looking at an example of Named Pipe or FIFO through a C program, exploring its use cases and also some of its benefits and drawbacks.

Example of Named Pipe or FIFO

Below is a C program that uses named pipes for example.

In this example, we create a named pipe using the mkfifo function with a specified path (/tmp/myfifo). Then, we fork a child process where the child process acts as a writer and the parent process acts as a reader. The writer process opens the named pipe for writing (O_WRONLY), writes a message to the pipe using the write function, and then closes the pipe. The reader process opens the named pipe for reading (O_RDONLY), reads the message from the pipe using the read function, and then closes the pipe. The parent process waits for the child process to finish using wait(NULL), and then removes the named pipe using unlink.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <sys/wait.h>

#define FIFO_PATH "/tmp/myfifo" // Path to the named pipe

void writer_process() {
   int fd;
   char message[] = "Hello, named pipe!";

   // Open the named pipe for writing
   fd = open(FIFO_PATH, O_WRONLY);
   if (fd == -1) {
      perror("open");
      exit(EXIT_FAILURE);
   }

   // Write the message to the named pipe
   write(fd, message, strlen(message) + 1);
   printf("Message sent: %s
", message); // Close the named pipe close(fd); } void reader_process() { int fd; char buffer[100]; // Open the named pipe for reading fd = open(FIFO_PATH, O_RDONLY); if (fd == -1) { perror("open"); exit(EXIT_FAILURE); } // Read the message from the named pipe read(fd, buffer, sizeof(buffer)); printf("Message received: %s
", buffer); // Close the named pipe close(fd); } int main() { pid_t pid; // Create the named pipe mkfifo(FIFO_PATH, 0666); // Fork a child process pid = fork(); if (pid == -1) { perror("fork"); exit(EXIT_FAILURE); } else if (pid == 0) { // Child process (writer) writer_process(); } else { // Parent process (reader) reader_process(); // Wait for the child process to finish wait(NULL); // Remove the named pipe unlink(FIFO_PATH); } return 0; }

Output

Message sent: Hello, named pipe!
Message received: Hello, named pipe!

Note− In this example, we demonstrate how named pipes facilitate interprocess communication, allowing data to be passed between independent processes using a first-in, first-out (FIFO) order. We may need appropriate permissions and error handling in a real-world scenario. Moreover, the path to the named pipe needs to be chosen appropriately to match your system's requirements.

Use Cases of Named Pipe or FIFO

Let us look at some use cases for Named Pipes or FIFOs below.

Interprocess Communication − Named pipes are commonly used for interprocess communication (IPC) between independent processes. They provide a simple and efficient way for processes to exchange data without sharing memory or having direct dependencies. Named pipes enable communication between processes running on the same machine or even across different systems when they have access to a shared file system.

Client-Server Communication − Named pipes are often employed in client-server architectures to establish communication channels between clients and servers. The server creates a named pipe and listens for client requests, while clients can connect to the server by opening the named pipe. This allows for seamless communication and data exchange between clients and the server.

Shell Scripting − Named pipes can be used in shell scripting to connect different commands or processes. By using named pipes, the output of one command can be piped into another command as input, enabling the chaining of multiple commands together. This provides flexibility in scripting and allows for the efficient flow of data between different components.

Data Streaming and Logging − Named pipes are useful for streaming data or log files between processes. For example, a process generating log information can write the logs to a named pipe, and another process can read from the pipe and perform further processing or storage of the log data. This allows for real-time processing and analysis of log information.

Distributed Computing − Named pipes can facilitate communication between processes in distributed computing environments. In scenarios where multiple processes are running on different machines and need to exchange data, named pipes can provide a reliable and efficient communication mechanism. They can be used to transmit data between distributed components, such as in distributed data processing frameworks or parallel computing applications.

System Monitoring and Control − Named pipes can be utilized in system monitoring and control applications. For instance, a monitoring process can write system metrics to a named pipe, and other processes or systems can read from the pipe to collect and analyze the metrics. This enables efficient monitoring and control of system resources and performance.

Benefits of Named Pipe or FIFO

The following benefits of named pipes (FIFOs) for interprocess interaction −

  • Simple and easy to use − Named pipes offer a simple and uncomplicated method for communication between processes. They operate on a straightforward FIFO model when information created by a single procedure is retrieved through another procedure in the exact same order.

  • Process independence − Operations with named pipes can communicate with one another. The procedures can talk to one another with no previous understanding or reliance so long as they're granted the right authorization for using the named pipe.

  • Interprocess communication − When a named pipe exists in a file system that is shared that both systems can access, it allows interaction among procedures that are operating on the exact same machine as well as among procedures that are operating on various systems.

  • Efficiency − Named pipes are a productive way to communicate between processes. They can effectively handle enormous quantities of data and depend on a buffering system.

Drawbacks of Named Pipe or FIFO

The following drawbacks of named pipes (FIFOs) for interprocess interaction−

  • Unidirectional communication − Named pipes support a one-way exchange from the writer's perspective to the audience member or the reverse because they are unidirectional.

  • Limited functionality − Named pipes offer a straightforward method of transmitting information and are comparatively simple. Advanced features like communication limitations, structures for data, and complex data serialization are not supported by them.

  • Blocking behavior − Both reading and writing activities on named pipes are perpetually blocked by default. A program will be restricted until the information is accessible or time is freed if it attempts to read from or write to a devoid pipe or a pipe that is full.

  • Limited error handling − The embedded abilities of named pipes could be improved. Additionally, there isn't an integrated system to deal with or recuperate from such mistakes if an error in communication takes place, like a pipe breaking or an operation ending abruptly.

Conclusion

It's crucial to take you're application's particular needs, limitations, and compromises into account when choosing whether or not you should utilize named pipes for IPC. Solutions IPC strategies like plugs, communication wait times, or shared storage might prove better suited based on the level of complexity and capabilities required.

Named pipes are a valuable tool for interprocess interaction in many circumstances, offering an immediate and efficient means between procedures.

Updated on: 17-Jul-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements