Inter-process communication-pipelines

Source: Internet
Author: User
Tags sprintf

1. Pipeline

Pipeline communication--can only be run on a single computer.

Pipeline: Must be half-duplex communication, can only flow to One direction (specified direction);

A pipeline is a concept of interprocess communication that constructs a one -way data Flow channel between processes to communicate. Data flows from one process to another through that channel in chronological order . It's like having a "pipe" in the process.

Model analysis

650) this.width=650; "Src=" Http://s5.51cto.com/wyfs02/M02/87/56/wKioL1feAjeT2okPAAAfbndOjpA516.png-wh_500x0-wm_3 -wmp_4-s_2808134401.png "title=" Qq20160918105536.png "alt=" Wkiol1feajet2okpaaafbndojpa516.png-wh_50 "/>

Pipeline implementation: Under the Linux (POSIX standard) operating system, pipelines are implemented through files. In the subsequent development of the operating system, the use of file access is still used in the pipeline, but the specific pipeline has moved from external memory to memory.

2. Nameless Pipe

Parent-child processes that can be used only for affinity relationships.

Pipe () Method: int pipe (int pipefd[2]);

The pipe method creates a pair of file descriptors that point to the same pipe file, and the 2 file descriptors are placed in the parameter PIPEFD array. PIPEFD[0] holds the read of the pipe file, pipefd[1] holds the write to the pipe file.

pipe files are opened 2 times during pipe operation, respectively, in read-only and write-only mode. From the basic logic of the pipeline, it is actually the outlet and entrance of the pipeline. As long as the 2 file descriptors are handed over to different processes, one-way communication between the 2 processes can be achieved.

Simple code for pipeline communication:

#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include < Fcntl.h>int main (void) {    pid_t pid;    int fd[2];     char buf[80];    int res = pipe (FD);   //fd[0]  fd[1]    if (res < 0) {          perror ("");        return -1;      }       pid = fork ();     if (pid == 0) {         close (fd[0]);         sleep (2);         sprintf (buf,  "I am child,  Who are you ");         write (Fd[1], buf, strlen (buf));         close (fd[1]); &NBSP;&NBSP;&NBSP;&NBSP;}ELSE&NBSP;IF (PID  > 0) {        close (fd[1]);          read (fd[0], buf, sizeof (BUF));         printf ("received a msg buf = %s\n",  buf);         close (fd[0]);    }else{         Perror ("");     }    return 0;}

Run results

650) this.width=650; "Src=" Http://s5.51cto.com/wyfs02/M01/87/5A/wKiom1feC4mTU9eQAAApaNhwKPE447.png-wh_500x0-wm_3 -wmp_4-s_3597145631.png "title=" Qq20160918113508.png "alt=" Wkiom1fec4mtu9eqaaapanhwkpe447.png-wh_50 "/>

Pause for 2 seconds before this result occurs.

Characteristics of pipeline communication:

(1), if the pipeline is empty, the party reading the data from the pipeline will block. Until there is new data in the pipeline.

(2), the data communication of the pipeline has FIFO characteristics, so as to avoid the confusion.

(3), the pipeline data read and send is not the number of times limit, but the pipeline is empty when the most important indicator.

(4), the use of such pipelines has one of the biggest limitations: only applicable to parent-child processes. As you can see from the design of the program, the creation of the pipeline is done by the parent process, and it is before the child process is created that the child process has a pipe file descriptor that allows the parent-child process to contract to hold the inlet or outlet of the pipeline.

(5), a pipeline can only achieve one-way data flow.

3, question: How to achieve a parent-child process a question and answer the communication mode?

Analysis: Because the pipeline has one-way data flow characteristics, is half-duplex, to achieve both sides of the communication, it must be full-duplex. At this point, 2 pipelines are required to complete this function.

Model analysis

650) this.width=650; "Src=" Http://s2.51cto.com/wyfs02/M00/87/5F/wKioL1felevTnmJ2AABT6outhNc518.png-wh_500x0-wm_3 -wmp_4-s_4114057154.png "title=" Qq20160918212524.png "alt=" Wkiol1felevtnmj2aabt6outhnc518.png-wh_50 "/>

Code to implement a one-to-one communication between parent-child processes:

#include <unistd.h> #include <stdlib.h> #include <string.h> #include <sys/wait.h> #include < Fcntl.h>int main (void) {    int fd1[2];  //pipe 1 file descriptor      int fd2[2];  //file Descriptor     int res = pipe (FD1) for pipeline 2;     if (res == -1) {        perror ("");     }       res = pipe (FD2);     if (res == -1) {        perror ("");     }       pid_t pid;    pid =  Fork ();     if (pid == 0) {          char child_speak[80] = {' h '};;         char buf[80];    &nBsp;   close (Fd1[0]);         close (fd2[1]);         while (strncmp (child_speak,  "quit",  4)  != 0) {              printf ("child :>");  &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SCANF ("%s",  child_speak);             sprintf (buf,  "%s",  child_speak);             write (Fd1[1], buf, strlen (BUF));             read (Fd2[0], buf, sizeof (buf ));         }        close (fd1[ 1]);         close (fd2[0]); &NBSP;&NBSP;&NBSP;&NBSP;}ELSE&NBSP;IF (PID  > 0) {&NBSP;&NBsp;      char parent_speak[80] = {' W '};         char buf[80];        close (fd1[1]);         close (Fd2[0]);         while ( STRNCMP (parent_speak,  "quit",  4)  != 0) {             read (fd1[0], buf, sizeof (BUF));             printf ("parent :>");         &NBSP;&NBSP;&NBSP;&NBSP;SCANF ("%s",  parent_speak);             sprintf (buf,  "%s",  parent_speak);             write (Fd2[1], buf, strlen (BUF));         }   &Nbsp;                close (FD1 [0]);         close (fd2[1]);         Int status;        wait (&status);     } Else{        perror ("");    }     return 0;}

Run results

650) this.width=650; "Src=" Http://s5.51cto.com/wyfs02/M00/87/62/wKiom1fel37SMAvlAAA9rSlCLoY573.png-wh_500x0-wm_3 -wmp_4-s_4056488026.png "title=" Qq20160918213235.png "alt=" Wkiom1fel37smavlaaa9rslcloy573.png-wh_50 "/>


(2), Popen () method

Popen () can execute command line content, fork a subprocess, let the child process execv the command line, write the standard output of the command line to the pipe file, and then return the Fife pointer of the pipeline file as the return value.

Popen is still a communication between parent and child processes.

The implementation code is as follows:

#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h>int main ( void) {    file *fp = popen ("ls -l",  "R");     if (fp == null) {        perror ("Popen error");         return -1;     }        char buf[80];    int ret;    while (! feof (FP)) {        ret = fread (buf, sizeof (BUF),  1, &NBSP;FP);         if (ret == 0) {              perror ("");             break;        }            printf ("%s",  buf);    }            return 0;}

Run results

650) this.width=650; "Src=" Http://s5.51cto.com/wyfs02/M01/87/60/wKioL1feoauSsQXkAAA2hF-jHIk679.png-wh_500x0-wm_3 -wmp_4-s_3565036252.png "title=" Qq20160918221555.png "alt=" Wkiol1feoaussqxkaaa2hf-jhik679.png-wh_50 "/>

4. Famous pipes (Named pipes)

Normal pipelines can only communicate between parent and child processes, and special means are required if you need to use pipelines to achieve communication between non-parent and child processes. A well-known pipeline is this technique, which means to name a pipe, so long as the process that knows the name of the pipe can use that pipeline to communicate.

The API Mkfifo you need to use

A well-known pipeline for primary use

The code is as follows: Write the party

#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <sys /types.h> #include <sys/stat.h> #include <fcntl.h>int main (void) {    int  ret;    char buf[80];    ret = mkfifo ("./tmp",  0755);   //Create a pipeline file     if (ret != 0) {          perror ("");        return -1;      }       int fd = open ("./tmp",  o_creat | o_wronly);   //Open the pipe file only. Returns the file descriptor for the pipeline file.     if (fd < 0) {         perror (" ");        return -1;     }        while (1) {        memset (buf, 0, sizeof (BUF));         sprintf (buf,  "This is writter");         write (fd,  Buf, strlen (BUF));         sleep (1);     }     return 0;}

code as follows: Read party

 #include <stdio.h> #include <unistd.h> #include <stdlib.h># include<string.h> #include <fcntl.h>int main (void) {    int fd;      char buf[80];    fd = open ("./tmp",  O_APPEND,  o_rdonly)  //Open the file as read-only     if (fd < 0) {          perror ("");        return -1;      }       while (1) {         memset (buf, 0, sizeof (BUF));         read ( Fd, buf, sizeof (BUF));         printf ("Resd a msg  : %s\n ",  buf);     }       return 0 ;}

Run results

650) this.width=650; "Src=" Http://s1.51cto.com/wyfs02/M00/87/63/wKiom1fern-DFhAyAAA85CGhHsA394.png-wh_500x0-wm_3 -wmp_4-s_3744507909.png "title=" Qq20160918231030.png "alt=" Wkiom1fern-dfhayaaa85cghhsa394.png-wh_50 "/>

650) this.width=650; "Src=" Http://s1.51cto.com/wyfs02/M01/87/64/wKiom1ferwKRh46GAACIwfZ8IeI852.png-wh_500x0-wm_3 -wmp_4-s_522570319.png "title=" Qq20160918231256.png "alt=" Wkiom1ferwkrh46gaaciwfz8iei852.png-wh_50 "/>

Summary of the famous pipeline file:

(1), two non-parent-child processes communicate through a well-known pipeline;

(2), pipeline files only need a process to create, other processes as long as there is, direct use on the line;

(3), Mkfifo creates a pipeline file in the file system and then maps it to a special area of memory, which can be used to implement FIFO data flow in any process that can open a pipeline file created by Mkfifo.

(4), if the data is read in a known pipeline, it will not continue to exist in the named pipeline.

(5), pipeline file is not really a file on disk, it is a memory area;



This article is from the "11586096" blog, please be sure to keep this source http://11596096.blog.51cto.com/11586096/1853840

Inter-process communication-pipelines

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.