Linux inter-process communication (IPC) Programming Practice (2) FIFO naming Pipeline

Source: Internet
Author: User

Linux inter-process communication (IPC) Programming Practice (2) FIFO naming Pipeline

In the previous article, we explained how to use anonymous pipelines to transmit data between processes, and also saw a defect in this method, these processes are started by a common ancestor process, which makes it inconvenient for us to exchange data between unrelated processes. Here, we will introduce another communication method of processes, named pipe, to solve the communication problem between irrelevant processes.

 

What is a named pipe?A named pipe is also called a FIFO file. It is a special type of file that exists in the file system as a file name, however, its behavior is similar to that of an unnamed pipeline (an anonymous pipeline. All things in Linux can be regarded as files, so the use of Named Pipes becomes very consistent with file operations and makes it easy to use, at the same time, we can also use it in the command like a common file name. FIFO only borrows a file system (named pipe is a special type of file, because everything in Linux is a file and it exists as a file name in the file system .) To name the MPs queue. Write mode processes write data to FIFO files, while read mode processes read data from FIFO files. When a FIFO file is deleted, the Pipeline Connection disappears. The advantage of FIFO is that we can identify pipelines through file paths, so as to establish connections between unrelated processes. Create a named pipe
# Include
 
  
# Include
  
   
Int mkfifo (const char * pathname, mode_t mode); // instance int main () {if (mkfifo ("p2", 0644) =-1) err_exit ("mkfifo error ");}
  
 
The mknod function can also create a named pipeline, but mknod is an old function, and the mkfifo function is simpler and more standard. Therefore, we recommend that you use mkfifo instead of mknod whenever possible.

What is the difference between FIFO and PIPE:

1) The anonymous pipeline is created and opened by the pipe function.

The named pipe is created by the mkfifo function and open with open.

2) The only difference between FIFO (named pipeline) and pipe (anonymous pipeline) is that they are created and opened in different ways. Once these tasks are completed, they have the same semantics.

Open a FIFO fileLike opening other files, a FIFO file can also be opened using an open call. Note that the mkfifo function only creates a FIFO file. You need to use the named pipe or open it. But there are two points to note: 1. A program cannot open a FIFO file in O_RDWR mode for read/write operations, and its behavior is not clearly defined, because, for example, a pipeline is opened in read/write mode, the process will read its own output, and we usually use FIFO only for one-way data transmission. 2. The first-in-first-out path name is passed to open, rather than a normal file. There are four methods to open a FIFO file:
open(const char *path, O_RDONLY);//1  open(const char *path, O_RDONLY | O_NONBLOCK);//2  open(const char *path, O_WRONLY);//3  open(const char *path, O_WRONLY | O_NONBLOCK);//4  

What is the blocking of open calls? Very simple. For a FIFO file opened in read-only mode (O_RDONLY), if the open call is blocked (that is, the second parameter is O_RDONLY ), unless a process opens the same FIFO in write mode, it will not return. If the open call is non-blocking (that is, the second parameter is O_RDONLY | O_NONBLOCK ), even if no other process opens the same FIFO file in write mode, the open call succeeds and returns immediately.
For a FIFO file opened in write-only mode (O_WRONLY), if the open call is blocked (that is, the second parameter is O_WRONLY), the open call is blocked, until a process opens the same FIFO file in read-only mode. If the open call is non-blocking (that is, the second parameter is O_WRONLY | O_NONBLOCK), open always returns immediately, however, if no other process opens the same FIFO file in read-only mode,-1 will be returned for the open call and the FIFO will not be opened.

The following example describes how two processes copy data through FIFO: Using pipelines, two processes perform file replication.

1. Process writefifo:

(1) read the file (the file name is obtained from the command line parameters)

(2) write the MPs queue myFifo (the MPs queue is created by this process)

(3) Close files and Pipelines

2. readfifo process:

(1) read pipe myFifo

(2) write the file [this file has been created and opened by a process]

(3) close the file

(4) Delete An MPs queue

// 1: writefifo int main (int argc, char * argv []) {if (argc <2) err_quit ("Usage:./writefifo
 
  
"); // Create a pipe if (mkfifo (" myFifo ", 0644) =-1) err_exit (" mkfifo error "); int outfd = open (" myFifo ", o_WRONLY); // open the FIFO int infd = open (argv [1], O_RDONLY); // open the file if (outfd =-1 | infd =-1) err_exit ("open file/fifo error"); char buf [BUFSIZ]; int readBytes; while (readBytes = read (infd, buf, sizeof (buf)> 0) {write (outfd, buf, readBytes) ;}close (infd); close (outfd );}
 

// 2: readfifo int main (int argc, char * argv []) {if (argc <2) err_quit ("Usage:./writefifo
 
  
"); Int outfd = open (argv [1], O_WRONLY | O_CREAT | O_TRUNC, 0644); // create and punch the file int infd = open (" myFifo ", O_RDONLY ); // enable the FIFO if (infd =-1 | outfd =-1) err_exit ("open file/fifo error"); char buf [BUFSIZ]; int readBytes; while (readBytes = read (infd, buf, sizeof (buf)> 0) {write (outfd, buf, readBytes);} close (outfd ); unlink ("myFifo"); // Delete FIFO}
 
Analysis: Both programs use the FIFO in blocking mode. To make it clearer, run writefifo and put it in the background. When the jobs command is called, we can see that it is indeed running in the background. After five seconds, we can call the jobs command again. We can see that the process writefifo is not finished yet and it is still running. The writefifo process's open call is blocked. When readfifo is not running, no other process opens the same FIFO in Read mode, so it remains waiting and open is blocked, no response is returned. Then, when the readfifo process is running (to view the performance, run in the time Command), the open call in writefifo returns, the process starts to work, and then ends the process. While the open call of readfifo is also in blocking mode, writefifo has been running, that is, another process opened the same FIFO in writing mode, so the open call returns immediately.

The preceding example shows the communication problem between two processes. That is to say, one process writes data to the FIFO file, while the other process reads data from the FIFO file. Imagine a problem where only one FIFO file is used. If multiple processes write data to the same FIFO file at the same time, what happens when only one read-only FIFO process reads data from the same FIFO file? It is normal that data blocks are staggered?

To solve this problem, write operations are made atomic. How can we make write operations atomic? The answer is simple. The system stipulates that, in a FIFO opened in O_WRONLY (blocking mode), if the length of the written data is smaller than the length of the data waiting for PIPE_BUF, or all bytes are written, or do not write a single byte. If all write requests are sent to a blocked FIFO, and the data length of each write request is smaller than or equal to PIPE_BUF bytes, the system will ensure that the data will not be intertwined.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.