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!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics



How to use Docker Desktop? Docker Desktop is a tool for running Docker containers on local machines. The steps to use include: 1. Install Docker Desktop; 2. Start Docker Desktop; 3. Create Docker image (using Dockerfile); 4. Build Docker image (using docker build); 5. Run Docker container (using docker run).

Docker process viewing method: 1. Docker CLI command: docker ps; 2. Systemd CLI command: systemctl status docker; 3. Docker Compose CLI command: docker-compose ps; 4. Process Explorer (Windows); 5. /proc directory (Linux).

Troubleshooting steps for failed Docker image build: Check Dockerfile syntax and dependency version. Check if the build context contains the required source code and dependencies. View the build log for error details. Use the --target option to build a hierarchical phase to identify failure points. Make sure to use the latest version of Docker engine. Build the image with --t [image-name]:debug mode to debug the problem. Check disk space and make sure it is sufficient. Disable SELinux to prevent interference with the build process. Ask community platforms for help, provide Dockerfiles and build log descriptions for more specific suggestions.

VS Code system requirements: Operating system: Windows 10 and above, macOS 10.12 and above, Linux distribution processor: minimum 1.6 GHz, recommended 2.0 GHz and above memory: minimum 512 MB, recommended 4 GB and above storage space: minimum 250 MB, recommended 1 GB and above other requirements: stable network connection, Xorg/Wayland (Linux)

The reasons for the installation of VS Code extensions may be: network instability, insufficient permissions, system compatibility issues, VS Code version is too old, antivirus software or firewall interference. By checking network connections, permissions, log files, updating VS Code, disabling security software, and restarting VS Code or computers, you can gradually troubleshoot and resolve issues.

VS Code is available on Mac. It has powerful extensions, Git integration, terminal and debugger, and also offers a wealth of setup options. However, for particularly large projects or highly professional development, VS Code may have performance or functional limitations.

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

How to back up VS Code configurations and extensions? Manually backup the settings file: Copy the key JSON files (settings.json, keybindings.json, extensions.json) to a safe location. Take advantage of VS Code synchronization: enable synchronization with your GitHub account to automatically back up all relevant settings and extensions. Use third-party tools: Back up configurations with reliable tools and provide richer features such as version control and incremental backups.
