Home  >  Article  >  System Tutorial  >  Named pipes (FIFO) in linux systems

Named pipes (FIFO) in linux systems

WBOY
WBOYforward
2024-02-15 13:40:03492browse

Linux system is an operating system that supports concurrent execution of multi-tasks. It can run multiple processes at the same time, thereby improving system utilization and efficiency. However, if data exchange and collaboration are required between these processes, some inter-process communication (IPC) methods need to be used, such as signals, message queues, shared memory, semaphores, etc. Among them, the famous pipe (FIFO) is a relatively simple and powerful IPC method. It allows two or more processes to transmit data through a file without caring about the content and format of the file. This article will introduce the method of named pipes (FIFO) in Linux systems, including the creation, opening, reading, writing, closing and deletion of famous pipes.

Named pipes (FIFO) in linux systems

A major limitation of the application of unnamed pipes is that they have no name, so they can only be used for inter-process communication with affinity. This limitation has been overcome after the introduction of named pipes (named pipes or FIFOs). FIFO is different from a pipe in that it provides a path name associated with it, which exists in the file system in the form of a FIFO file. In this way, even processes that are not related to the process that created the FIFO can communicate with each other through the FIFO as long as they can access the path (between the process that can access the path and the process that created the FIFO). Therefore, there is no correlation through the FIFO. Processes can also exchange data. It is worth noting that FIFO strictly follows first in first out (first in first out). Reading from pipes and FIFO always returns data from the beginning, and writing to them adds data to the end. They do not support file location operations such as lseek().
The buffer of the pipe is limited (the pipe system exists in memory, and a page size is allocated for the buffer when the pipe is created)
What the pipe transmits is an unformatted byte stream, which requires the reader and writer of the pipe to agree on the format of the data in advance, such as how many bytes count as a message (or command, or record), etc.

FIFO often has multiple writing processes and one reading process.

FIFO opening rules:

  1. If the current open operation is to open the FIFO for reading, if a corresponding process has already opened the FIFO for writing, the current open operation will return successfully; otherwise, it may be blocked until a corresponding process opens the FIFO for writing (the current open operation The blocking flag is set); or, returns successfully (the current open operation does not have the blocking flag set).
  2. If the current open operation is to open the FIFO for writing, if a corresponding process has already opened the FIFO for reading, the current open operation will return successfully; otherwise, it may block until a corresponding process opens the FIFO for reading (the current open operation The blocking flag is set); or, an ENXIO error is returned (the blocking flag is not set for the current open operation).

In short, in one sentence, once the blocking flag is set and mkfifo is called to establish it, the reading and writing at both ends of the pipe must be opened separately. If either side is not opened, it will be blocked when open is called.

Read data from FIFO:

Convention: If a process blocks the opening of the FIFO in order to read data from the FIFO, then the read operation within the process is called a read operation with the blocking flag set. (This means that I now need to open a famous pipe to read data!)

If a process writes to open the FIFO, and there is no data in the current FIFO (it can be understood that both ends of the pipe have been established, but the writing end has not yet started writing data!)

  1. Then for the read operation with the blocking flag set, it will always be blocked (that is, blocked and waiting for data. It does not consume CPU resources. This process synchronization method is very efficient for the CPU.)
  2. For read operations without setting the blocking flag, -1 is returned, and the current errno value is EAGAIN, reminding you to try again later.

For read operations with the blocking flag set (see the convention above)
There are two reasons for blocking

  1. FIFO内有数据,但有其它进程在读这些数据
  2. FIFO内没有数据。解阻塞的原因则是FIFO中有新的数据写入,不论信写入数据量的大小,也不论读操作请求多少数据量。

读打开的阻塞标志只对本进程第一个读操作施加作用,如果本进程内有多个读操作序列,则在第一个读操作被唤醒并完成读操作后,其它将要执行的读操作将不再阻塞,即使在执行读操作时,FIFO中没有数据也一样,此时,读操作返回0。

注:如果FIFO中有数据,则设置了阻塞标志的读操作不会因为FIFO中的字节数小于请求读的字节数而阻塞,此时,读操作会返回FIFO中现有的数据量。

向FIFO中写入数据:

约定:如果一个进程为了向FIFO中写入数据而阻塞打开FIFO,那么称该进程内的写操作为设置了阻塞标志的写操作。

对于设置了阻塞标志的写操作:

  1. 当要写入的数据量不大于PIPE_BUF时,linux将保证写入的原子性。如果此时管道空闲缓冲区不足以容纳要写入的字节数,则进入睡眠,直到当缓冲区中能够容纳要写入的字节数时,才开始进行一次性写操作。(PIPE_BUF ==>> /usr/include/linux/limits.h)
  2. 当要写入的数据量大于PIPE_BUF时,linux将不再保证写入的原子性。FIFO缓冲区一有空闲区域,写进程就会试图向管道写入数据,写操作在写完所有请求写的数据后返回。

对于没有设置阻塞标志的写操作:

  1. 当要写入的数据量大于PIPE_BUF时,linux将不再保证写入的原子性。在写满所有FIFO空闲缓冲区后,写操作返回。
  2. 当要写入的数据量不大于PIPE_BUF时,linux将保证写入的原子性。如果当前FIFO空闲缓冲区能够容纳请求写入的字节数,写完后成功返回;如果当前FIFO空闲缓冲区不能够容纳请求写入的字节数,则返回EAGAIN错误,提醒以后再写;

简单描述下上面设置了阻塞标志的逻辑
设置了阻塞标志

if (buf_to_write then
 if ( buf_to_write > system_buf_left ) //保证写入的原子性,要么一次性把buf_to_write全都写完,要么一个字节都不写!
 then
  block ;
  until ( buf_to_write else
  write ;
 fi
else
 write ; //不管怎样,就是不断写,知道把缓冲区写满了才阻塞
fi

管道写端 pipe_read.c

/pipe_read.c

#include 
#include 
#include 
#include 
#include 
#include 
#include 

#define FIFO_NAME "/tmp/my_fifo"
#define BUFFER_SIZE PIPE_BUF

int main()
{
int pipe_fd;
int res;

int open_mode = O_RDONLY;
char buffer[BUFFER_SIZE + 1];
int bytes = 0;

memset(buffer, '\0', sizeof(buffer));

printf("Process %d opeining FIFO O_RDONLY\n", getpid());
pipe_fd = open(FIFO_NAME, open_mode);
printf("Process %d result %d\n", getpid(), pipe_fd);

if (pipe_fd != -1)
{
do{
res = read(pipe_fd, buffer, BUFFER_SIZE);
bytes += res;
printf("%d\n",bytes);
}while(res > 0);
close(pipe_fd);
}
else
{
exit(EXIT_FAILURE);
}

printf("Process %d finished, %d bytes read\n", getpid(), bytes);
exit(EXIT_SUCCESS);
}

管道读端 pipe_write.c

//pipe_write.c

#include   
#include   
#include   
#include   
#include   
#include   
#include   
  
#define FIFO_NAME "/tmp/my_fifo"  
#define BUFFER_SIZE PIPE_BUF  
#define TEN_MEG (1024 * 100)  
  
int main()  
{  
    int pipe_fd;  
    int res;  
    int open_mode = O_WRONLY;  
  
    int bytes = 0;  
    char buffer[BUFFER_SIZE + 1];  
  
    if (access(FIFO_NAME, F_OK) == -1)  
    {  
        res = mkfifo(FIFO_NAME, 0777);  
        if (res != 0)  
        {  
            fprintf(stderr, "Could not create fifo %s\n", FIFO_NAME);  
            exit(EXIT_FAILURE);  
        }  
    }  
  
    printf("Process %d opening FIFO O_WRONLY\n", getpid());  
    pipe_fd = open(FIFO_NAME, open_mode);  
    printf("Process %d result %d\n", getpid(), pipe_fd);  
  
   //sleep(20);
    if (pipe_fd != -1)  
    {  
        while (bytes if (res == -1)  
            {  
                fprintf(stderr, "Write error on pipe\n");  
                exit(EXIT_FAILURE);  
            }  
            bytes += res;  
        printf("%d\n",bytes);
        }  
        close(pipe_fd);  
    }  
    else  
    {  
        exit(EXIT_FAILURE);  
    }  
  
    printf("Process %d finish\n", getpid());  
    exit(EXIT_SUCCESS);  
}

本文介绍了Named pipes (FIFO) in linux systems的方法,包括有名管道的创建、打开、读写、关闭和删除等方面。通过了解和掌握这些知识,我们可以更好地使用有名管道(FIFO)来实现进程间通信,提高系统的性能和可靠性。当然,Named pipes (FIFO) in linux systems还有很多其他的特性和用法,需要我们不断地学习和探索。希望本文能给你带来一些启发和帮助。

The above is the detailed content of Named pipes (FIFO) in linux systems. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:lxlinux.net. If there is any infringement, please contact admin@php.cn delete