Inter-process communication in Linux: Named Pipe-mkfifo

Source: Internet
Author: User

From: http://cpp.ezbty.org/content/science_doc/linux%E4%B8%8B%E8%BF%9B%E7%A8%8B%E9%97%B4%E9%80%9A%E4%BF%A1%EF%BC%9A%E5%91%BD%E5%90%8D%E7% AE %A1%E9%81%93_mkfifo

SummaryThere are many methods for inter-process communication. FIFO and pipelines are the oldest and a relatively simple communication mechanism. One advantage of FIFO over pipelines is that FIFO requires only two processes to be on the same host, rather than the kinship between processes. FIFO is a file stored in the file system and can be operated using functions such as open, read, and write. This article summarizes the network and apue discussions on FIFO, and also references the Linux system manual.

Directory [Hide]
    1. FIFO (Named Pipe) Overview
    2. Mkfifo Function
    3. Naming pipeline read/write rules
      1. Read data from FIFO
      2. Write Data from FIFO
    4. FIFO example
FIFO (Named Pipe) Overview

FIFO is a process communication mechanism, which breaks through the restrictions of communication between unrelated processes in the pipeline, so that all processes in the same host can communicate. FIFO is a file type. In the stat structure, st_mode indicates whether a file node is a FIFO node. You can use the macro s_isfifo to test this.

When a FIFO is stored in a file system, you only need to open the file in the process of communication. Of course, as a special file, FIFO has some different common file features. The following will detail its read/write rules in detail, which are somewhat different from those proficient in files.

We can use open, read, and write to operate FIFO files to achieve inter-process communication. In a shell environment, you can also use FIFO directly. In this case, there are some associations with rewriting. Generally, the system provides mkfifo for use.ProgramCreate a FIFO file. This program actually uses the mkfifo system call to complete this task.

Mkfifo Function

Mkfifo creates a FIFO with the specified name. Its function prototype is as follows:

# Include <sys/STAT. h>
Int Mkfifo ( Const Char * Pathname, mode_t Mode ) ;
Return Value: successful, 0 ; Failed, - 1

 

The pathname parameter specifies the FIFO path to be created, and the mode parameter specifies the FIFO access mode to be created. This access will work with the umask process of the current process to generate the permission mode of the actual application.

When mkfifo returns-1, it indicates that an error is encountered during the creation process. errno is set. You can check errno For further information:

    • Eacces: the directory where the path is located does not allow execution Permissions
    • Eexist: the path already exists. In this case, the path is a symbolic link, whether it is suspended or not.
    • Enametoolong: either all file names are greater than path_max, or individual file names are larger than name_max. There is no limit on the file name length in the GNU system, but it may exist in other systems.
    • Enoent: the directory does not exist or is a suspended link.
    • Enotdir: The Directory part is not a directory.
    • Erofs: The Path points to a read-only file system.

 

Naming pipeline read/write rules

FIFO is also called a named pipeline. In fact, it is similar to the pipeline in many aspects. The following discussions on rules are very similar.

Read data from FIFO

Convention: if a process blocks access to the first-in-first-out (FIFO) to read data from the first-out (FIFO), The read operation in the process is a read operation with a blocking flag set.

    • If a process writes to enable FIFO and the current FIFO is empty, the read operation with the blocking flag is blocked until data can be read; for read operations without a blocking sign, 0 bytes are returned, and the current errno value is eagain, prompting you to try again later.
    • For read operations with the blocking flag configured, there are two reasons for blocking: 1. There are data in the current FIFO, but other processes are reading the data; II. The FIFO is empty.
      The reason for blocking is that there are new data writes in the FIFO, regardless of the size of the data written or the amount of data requested by the read operation, as long as there is data written.
    • The read blocking mark only applies to the first read operation of the process. If there are multiple read operation sequences in the process, after the first read operation is awakened and the read operation is completed, other read operations to be executed will not be blocked, even if there is no data in the FIFO when the read operation is executed (at this time, the read operation returns 0 ).
    • If no process write is enabled, the read operation with the blocking flag set will be blocked.
    • If there is data in the FIFO, the read operation with the blocking mark will not be blocked because the number of bytes in the FIFO is smaller than the number of bytes requested. In this case, the read operation will return the existing data volume in the FIFO.
Write Data from FIFO

Convention: if a process blocks the opening of the FIFO to write data to the FIFO, the write operation in the process is a write operation with a blocking flag.

The length of FIFO is an important factor to consider. The system has a limit on the Data Length that can exist in a FIFO at any time. It is defined by # define pipe_buf in the header file limits. h. In Linux and many other UNIX-like systems, the value is usually 4096 bytes, and in Red Hat fedora9 it is 4096, but in some systems it may be as small as 512 bytes.

This restriction is not important for read processes with only one FIFO write process and one FIFO read process, however, it is common to use only one FIFO and allow multiple different processes to send requests to one FIFO read process. If several different programs try to write data to the FIFO at the same time, it is critical to ensure that data blocks from different programs are not staggered. That is to say, each write operation must be "Atomic ".

Write operation with blocking flag set:

    • When the data volume to be written is not greater than pipe_buf, Linux ensures the atomicity of writing. If the idle buffer of the pipeline is insufficient to accommodate the number of bytes to be written, the system goes to sleep until the buffer can accommodate the number of bytes to be written. That is, when the length of the written data is less than or equal to pipe_buf, it is a one-time action to write data in all or one byte, depending on whether there is sufficient buffer in the FIFO.
    • When the data volume to be written is greater than pipe_buf, Linux will no longer guarantee the atomicity of writing. As soon as the FIFO buffer has an idle area, the write process will attempt to write data to the pipeline, and the write operation will return after writing all the data written by the request.

Write operations without blocking flag settings:

    • When the data volume to be written is not greater than pipe_buf, Linux ensures the atomicity of writing. If the current FIFO idle buffer can accommodate the number of bytes written by the request, the result is returned successfully. If the current FIFO idle buffer cannot accommodate the number of bytes written by the request, the eagain error is returned, remind me to write it later.
    • When the data volume to be written is greater than pipe_buf, Linux will no longer guarantee the atomicity of writing. After the buffer is fully written into all the FIFO idle buffers, the write operation returns.
FIFO example

This section provides an example of using FIFO, which shows two typical scenarios of using FIFO.

Create FIFO

# Include <stdlib. h>
# Include <stdio. h>
# Include <sys/types. h>
# Include <sys/STAT. h>
Int Main ( )
{
Int Res = Mkfifo ( "/Tmp/my_fifo" , 0777 ) ;
If ( Res = 0 )
{
Printf ( "FIFO created\ N" ) ;
}
Exit ( Exit_success ) ;
}

 

Use FIFO

# Include <errno. h>
# Include <sys/STAT. h>
# Include <fcntl. h>

FIFO "/Tmp/my_fifo"
// This program reads data from a FIFO and prints the read data to the standard output.
// Exit if the character "Q" is read
Int Main( Int Argc, Char ** Argv )
{
Char Buf_r [ 100 ] ;
Int FD ;
Int Nread ;
If ( ( Mkfifo ( FIFO, o_creat ) < 0 ) && ( Errno ! = Eexist ) )
{
Printf ( "You cannot create a FIFO instance.\ N" ) ;
Exit ( 1) ;
}

Printf("Prepare to read data\ N");
FD=Open(FIFO, o_rdonly, 0);
If(FD= -1)
{
Perror("Enable FIFO");
Exit(1);
}

while ( 1 )
{
If ( nread = Read ( FD, buf_r, 100 ) ) = - 1 )
{
If ( errno / span> = eagain ) printf ( "no data \ n " ) ;
}

// Assume exit when Q is obtained
If(Buf_r[0]='Q') Break;

Buf_r[Nread]=0;
Printf("Data read from FIFO is: % s\ N", Buf_r);
Sleep(1);
}

}

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.