Linux interprocess communication (IPC) programming Practice (ii) FIFO Named pipes

Source: Internet
Author: User

in the previous article , we explain how to use anonymous pipelines to pass data between processes, and also see a flaw in the way that these processes are initiated by a common ancestor process, which makes it inconvenient to exchange data between unrelated processes. Here's another way to communicate the process-Named pipes-to address the communication issues between unrelated processes.

What is a named pipeA named pipe is also known as a FIFO file, which is a special type of file that exists as a file name in the filesystem, but behaves like a previously unnamed pipe (anonymous pipe).     because everything in Linux can be considered as a file, the use of named pipes becomes very uniform with file operations and makes it very easy to use. At the same time, we can use the command in the same way as the usual file name. fifo just borrowed the file system ( File system, Named pipes are special types of files because linux path to the file to identify the pipeline, allowing connections to be made between unrelated processes Create a named pipe
#include <sys/types.h>  #include <sys/stat.h>  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 pipe, but Mknod is an older function, and using the MKFIFO function is simpler and more prescriptive, so it is recommended to use MKFIFO instead of mknod whenever possible.

The difference between FIFO and pipe:

1) anonymous pipes are created and opened by the pipe function.

Named pipes are created by the Mkfifo function and opened with open.

2) The only difference between a FIFO (named pipe) and a pipe (anonymous pipe) is that they are created and opened in a different way, but they have the same semantics after the work is done.

Open FIFO fileLike opening other files, FIFO files can also be opened using the open switch.   Note that the MKFIFO function simply creates a FIFO file to use a named pipe or open it. But there are two points toNote, 1, is the program can not beo_rdwr ModeThe FIFO file is opened for read and write operations, and its behavior is not explicitly defined, because if a pipe is opened in read/write mode, the process will read back its output, and we usually use FIFO only for one-way data passing. 2, is passed to the open call is the FIFO path name, but not the normal file. There are typically 4 ways 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  

blocking of open callsWhat's the matter? Very simply, for FIFO files opened in read-only mode (o_rdonly), if the open call is blocked (that is, the second parameter is o_rdonly), it will not return unless there is a process that opens the same FIFO in write mode. If an open call is non-blocking (that is, the second argument is O_rdonly | O_nonblock), the open call succeeds and returns immediately, even if no other process opens the same FIFO file in write mode.
For FIFO files 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 as read-only If the open call is non-blocking (that is, the second argument is O_wronly | O_nonblock), open always returns immediately, but if no other process opens the same FIFO file in read-only mode, the open call returns 1, and the FIFO is not opened.

The following example shows two processes through FIFO -copy data : using Pipelines , Two processes for file replication.

1. process Writefifo:

(1) Read the file ( the file name is obtained from the command line arguments )

(2) Write Pipeline Myfifo ( pipeline created by this process )

(3) close files and pipelines

2. process Readfifo:

(1) Read Pipeline Myfifo

(2) Write File [ The file has process created and opened ]

(3) Close File

(4) Delete Pipeline

1:writefifo  int main (int argc, char *argv[])  {      if (argc < 2)          Err_quit ("Usage:./writefifo < Read-file-name> ");        Create Pipeline      if (Mkfifo ("Myfifo", 0644) = =-1)          err_exit ("Mkfifo error");      int outfd = open ("Myfifo", o_wronly);   Open FIFO      int infd = open (argv[1], o_rdonly);     Open 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 < Write-file-name> ");        int outfd = open (argv[1], o_wronly| O_creat| O_trunc, 0644);  Create and punch the file      int infd = open ("Myfifo", o_rdonly);    Open 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: Two programs use the FIFO of the blocking mode, in order to get a clearer view of how blocking is all about, first we run Writefifo and put it in the background to run. When you call the jobs command, you can see that it is actually running in the background, after 5 seconds, and then calling the Jobs command, you can see that the process Writefifo is not over yet and it continues to run. Because the open call of the Writefifo process is blocked, the ReadfifoThere is no other process to open the same FIFO in read mode, so it is waiting, open is blocked, and no return. Then, when we processReadfifoAt run time (in order to see performance, run in the time command), the open call in Writefifo returns, the process begins to work, and then the process ends. While Readfifo's open call is blocking mode, the Writefifo is already running, that is, another process has opened the same FIFO in writing, so the open call returns immediately.
The previous example is a communication problem between two processes, that is, one process writes data to a FIFO file, while another process reads the data in a FIFO file. Imagine a problem, using only a FIFO file, if there are multiple processes simultaneously to the same FIFO file to write data, and only a read FIFO process in the same FIFO file to read data, what happens when the data block interleaving is normal?
In order to solve this problem, it is to let the atomization of the write operation. How can I make a write operation atomized? The answer is simple: In a FIFO opened in o_wronly (that is, blocking mode), if the length of the data being written is less than the waiting pipe_buf, either all bytes are written, or none of the bytes are written. If all of the write requests are destined for a blocking FIFO, and the data length of each write request is less than or equal to Pipe_buf bytes, the system ensures that the data will never be interleaved. (Refer to my previous blog post).




Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Linux interprocess communication (IPC) programming Practice (ii) FIFO Named pipes

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.