interprocess communication ipc-Anonymous pipe (pipe) and Named Pipes (FIFO)

Source: Internet
Author: User

How does the internal pipeline implement-size, organization, ring queue?


I. There are several ways of interprocess communication, this article mainly explains the understanding of pipelines. Pipelines are divided into anonymous pipes and named pipes.

(1) piping (pipe): also known as anonymous pipes. is a half-duplex mode of communication in which data can only flow in one direction and can only be used between processes that have affinity. A process's affinity usually refers to a parent-child process relationship.
(2) named pipe (named pipe or FIFO): a well-known pipe is also a half-duplex mode of communication, but it allows communication between unrelated processes.


Two. Piping    

1. Characteristics of the pipeline:

(1) The pipeline is half-duplex, the data can only flow in one direction; When the two sides communicate, it is necessary to establish two pipelines;

(2) can only be used between parent-child processes or sibling processes (affinity-related processes);

(3) Separate form a separate file system: The pipeline is a file for the process at both ends of the pipe, but it is not an ordinary file, it does not belong to a file system, but is a separate file system, and only exists in memory.

(4) read and write data: a process that writes to the pipeline is read out by the process at the other end of the pipeline. The content that is written is added to the end of the pipe buffer every time, and the data is read from the head of the buffer each time.


2. Communication steps

2.1 Creating pipelines

650) this.width=650; "src=" http://blog.chinaunix.net/attachment/201205/29/26833883_133829008404bu.png "border=" 0 " height= "width=" 507 "style=" border:0px; alt= "26833883_133829008404bu.png"/>

Use the pipe () function to create a pipeline that opens a buffer (called a pipe) in the kernel for communication. The pipe function call successfully returned 0, and the call failed to return-1.

a pipeline is a method of communicating based on a file descriptor. When a pipeline is established, it creates two file descriptors fd[0] and fd[1]. where fd[0] is fixed for read pipelines, while fd[1] is fixed for write pipelines , general file I/O functions can be used to manipulate pipelines (except Lseek). The rules for reading and writing pipelines are as follows:


To read data from the pipeline:

    • If the write end of the pipeline does not exist, it is considered that the end of the data has been read, the Read function returns the number of read bytes is 0;

    • When the write side of the pipeline exists, if the number of bytes requested is greater than pipe_buf, the number of existing data bytes in the pipeline is returned, and if the requested number of bytes is not greater than pipe_buf, the number of existing data bytes in the pipeline is returned (in this case, the amount of data in the pipeline is less than the requested amount of data) or return the requested number of bytes (in this case, the amount of data in the pipeline is not less than the requested amount of data). Note: (Pipe_buf is defined in Include/linux/limits.h, different kernel versions may vary.) POSIX.1 requires a minimum of 512 bytes for pipe_buf, and 4096 in Red Hat 7.2).


To write data to the pipeline:

    • When writing data to a pipeline, Linux does not guarantee the atomicity of writes, and the pipeline buffer has an idle area, and the write process attempts to write data to the pipeline. If the read process does not read the data in the pipeline buffer, the write operation will be blocked.
      Note: Writing data to a pipeline is meaningful only if the read side of the pipeline exists. Otherwise, the process that writes data to the pipeline receives the sifpipe signal from the kernel, which the application can process or ignore (the default action is the application termination).



2.2 Creating child processes

Creating a nameless pipe by itself has no practical meaning. We fork a sub-process, and then through the pipeline to achieve communication between the parent-child process (that is, there are two processes in the relationship, where the kinship refers to having a common ancestor).

2.3 Parent Process closes pipe read end, child process closes pipe write end


3. Code Validation

3.1 Checking the pipe size

  1  #include <stdio.h>  2  #include <stdlib.h>  3 # Include<unistd.h>  4 int main ()   5 {  6      int fd[2];  7     int count=0;  8      if (Pipe (FD) <0)   9     { 10          perror ("Fail to create pipe"); 11          exit (exit_failure);  12     } 13      while (1)  14     { 15          write (Fd[1], "a", sizeof (char)); 16          printf ("count=%d.\n", ++count); 17     } 18      return 0; 19 } 

Running Result: 65536=64k


3.2 The study of reading and writing rules

A. Reading data from A pipeline

<1> write end does not exist

  1  #include <stdio.h>  2  #include <unistd.h>  3 # Include<stdlib.h>  4 int main ()   5 {  6      int n;  7     int fd[2];  8      int count=0;  9     char buf[100]={0}; 10   11     if (Pipe (FD) <0)  12     { 13          perror ("Fail to create pipe");  14          exit (exit_failure); 15      } 16     close (fd[1]); 17  18      if ((N=read (fd[0],buf,sizeof (BUF)) <0)  19     { 20          pError ("Fail to read pipe");  21         exit ( Exit_failure);  22     } 23     printf ("read % D bytes:%s\n ", n,buf);  24     return 0; 25 }

Run Result: Read 0 bytes:

<2> when the write end is present

The parent process writes data to the pipeline, and the child process reads the data from the pipeline

#include  <stdio.h> #include  <stdlib.h> #include  <errno.h> #include  < String.h> #define &NBSP;N&NBSP;10#DEFINE&NBSP;MAX&NBSP;100INT&NBSP;CHILD_READ_PIPE (INT&NBSP;FD) {     char buf[n];    int n = 0;    while (1)     {        n = read (fd,buf,sizeof (BUF) );        buf[n] =  ';         printf ("read %d bytes : %s\n", N,buf);         if (strncmp (buf, "Quit", 4)  == 0)              break;    }    return 0;} Int father_write_pipe (INT&NBSP;FD) {    char buf[max] = {0};        while (1)     {        printf (">");         fgets (Buf,sizeof (BUF), stdin);         buf[ Strlen (BUF) -1] =  ' + ';         write (Fd,buf,strlen (BUF));         sleep (1);         if ( STRNCMP (buf, "Quit", 4)  == 0)              break;    }    return 0;} Int main () {    int pid;    int fd[2];     if (Pipe (FD)  < 0)     {         Perror ("Fail to pipe");         exit (EXIT_FAILURE);     }    if ((Pid = fork ()) &NBsp;< 0)     {        perror ("Fail to  fork ");         exit (exit_failure);     }     else if (pid == 0)     {         close (fd[1]);         child_read_pipe (fd[0]);     }    else    {             close (Fd[0]);         father_ Write_pipe (fd[1]);     }        exit (EXIT_SUCCESS);}





This article is from the "sunshine225" blog, make sure to keep this source http://10707460.blog.51cto.com/10697460/1762775

interprocess communication ipc-Anonymous pipe (pipe) and Named Pipes (FIFO)

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.