Named pipes (FIFO) in linux systems
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.
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:
- 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).
- 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!)
- 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.)
- 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
- FIFO内有数据,但有其它进程在读这些数据
- FIFO内没有数据。解阻塞的原因则是FIFO中有新的数据写入,不论信写入数据量的大小,也不论读操作请求多少数据量。
读打开的阻塞标志只对本进程第一个读操作施加作用,如果本进程内有多个读操作序列,则在第一个读操作被唤醒并完成读操作后,其它将要执行的读操作将不再阻塞,即使在执行读操作时,FIFO中没有数据也一样,此时,读操作返回0。
注:如果FIFO中有数据,则设置了阻塞标志的读操作不会因为FIFO中的字节数小于请求读的字节数而阻塞,此时,读操作会返回FIFO中现有的数据量。
向FIFO中写入数据:
约定:如果一个进程为了向FIFO中写入数据而阻塞打开FIFO,那么称该进程内的写操作为设置了阻塞标志的写操作。
对于设置了阻塞标志的写操作:
- 当要写入的数据量不大于PIPE_BUF时,linux将保证写入的原子性。如果此时管道空闲缓冲区不足以容纳要写入的字节数,则进入睡眠,直到当缓冲区中能够容纳要写入的字节数时,才开始进行一次性写操作。(PIPE_BUF ==>> /usr/include/linux/limits.h)
- 当要写入的数据量大于PIPE_BUF时,linux将不再保证写入的原子性。FIFO缓冲区一有空闲区域,写进程就会试图向管道写入数据,写操作在写完所有请求写的数据后返回。
对于没有设置阻塞标志的写操作:
- 当要写入的数据量大于PIPE_BUF时,linux将不再保证写入的原子性。在写满所有FIFO空闲缓冲区后,写操作返回。
- 当要写入的数据量不大于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!

Creating graphical user interface (GUI) applications is a fantastic way to bring your ideas to life and make your programs more user-friendly. PyGObject is a Python library that allows developers to create GUI applications on Linux desktops using the

Arch Linux provides a flexible cutting-edge system environment and is a powerfully suited solution for developing web applications on small non-critical systems because is a completely open source and provides the latest up-to-date releases on kernel

Due to its Rolling Release model which embraces cutting-edge software Arch Linux was not designed and developed to run as a server to provide reliable network services because it requires extra time for maintenance, constant upgrades, and sensible fi
![12 Must-Have Linux Console [Terminal] File Managers](https://img.php.cn/upload/article/001/242/473/174710245395762.png?x-oss-process=image/resize,p_40)
Linux console file managers can be very helpful in day-to-day tasks, when managing files on a local machine, or when connected to a remote one. The visual console representation of the directory helps us quickly perform file/folder operations and sav

qBittorrent is a popular open-source BitTorrent client that allows users to download and share files over the internet. The latest version, qBittorrent 5.0, was released recently and comes packed with new features and improvements. This article will

The previous Arch Linux LEMP article just covered basic stuff, from installing network services (Nginx, PHP, MySQL, and PhpMyAdmin) and configuring minimal security required for MySQL server and PhpMyadmin. This topic is strictly related to the forme

Zenity is a tool that allows you to create graphical dialog boxes in Linux using the command line. It uses GTK , a toolkit for creating graphical user interfaces (GUIs), making it easy to add visual elements to your scripts. Zenity can be extremely u

Some may describe it as their passion, while others may consider it a stress reliever or a part of their daily life. In every form, listening to music has become an inseparable part of our lives. Music plays different roles in our lives. Sometimes it


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Atom editor mac version download
The most popular open source editor
