UNIX processes using C/C++
  • 🍴The fork system call
  • ⌚The wait system call
  • 🆔Process ID
  • 🔌Signals in UNIX
    • 🗄️Signal Handlers
  • 🥃Executing system commands
  • 📁Sharing information between processes
    • 🕚Bidirectional pipe
  • 🖥️Applications
    • 💻Console Application 1
    • 💻Console Application 2
  • ⚽Named pipe FIFO
Powered by GitBook
On this page
  • Output
  • Output after reading from FIFO

Named pipe FIFO

In this section, we shall see what are FIFOs and how they work

PreviousConsole Application 2

Last updated 2 years ago

A FIFO special file (a named pipe with no extension) is similar to a pipe, except that it is accessed as part of the filesystem. It can be opened by multiple processes for reading or writing. When processes are exchanging data via the FIFO, the kernel passes all data internally without writing it to the filesystem.

Note: Opening the read or write end of a FIFO blocks until the other end is also opened (by another process or thread).

There are 2 ways of making a FIFO file:

  • Using the command mkfifo in the terminal itself

mkfifo filename
  • Creating a FIFO in the program itself

Example:

#include <stdio.h>
#include <unistd.h>

#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include <fcntl.h>  // for open() function

int main(){
    // 0777 are the permission bits in octal which allows any user/process to read/write from/to the FIFO
    if(mkfifo("myfifo", 0777) == -1){
        if(errno == EEXIST)
            printf("FIFO already exists\n");
        else
            printf("There was some unexpected error\n");
    }
    printf("Opening FIFO...\n");
    int fd = open("myfifo", O_WRONLY);

    printf("FIFO opened\n");
    char str[15] = "Saptarshi Dey\n";

    if(write(fd, str, sizeof(str)) == -1)
        return errno;
    
    printf("Data written to FIFO\n");
    close(fd);  // close the file descriptor
    printf("Closed\n");

    return 0;
}

Output

FIFO already exists
Opening FIFO...

The process stops there until we have another process reading from the FIFO

So we run this command in the same directory as the FIFO

cat myfifo  // command
Saptarshi Dey  // output

Output after reading from FIFO

FIFO already exists
Opening FIFO...
FIFO opened
Data written to FIFO
Closed
⚽
Link to FIFO manual
Link to open function manual