The pipeline of inter-process communication between Linux

Source: Internet
Author: User
Tags stdin

LinuxPipeline of interprocess communication1.Classification of pipelines:

By name, pipelines are divided into famous pipes and anonymous pipelines.

2. nickname pipeline

A pipeline is a way of one-way communication between processes, because its communication is only one direction, so the following disadvantages:

1. communication is only a single direction, communication is too limited

2. Its buffer size is certain, and after the buffer is full, it cannot continue to write data.

3. only unformatted byte streams are transmitted through the pipeline.

4. can only be used between affinity processes, such as parent-child processes, sibling processes.

3. creation of anonymous pipelines

pipeline creation using functions Pipe , its prototype is:

#include <unistd.h>intpipe (int pipefd[2]);

function parameter pipefd[2] is a shaped array, can be used as a general file descriptor, the pipe read end with pipefd[0] , the pipe write end with pipefd[1], the creation of a successful, then return 0, Failure returns -1, after the pipeline is created, you can

treated as a general document, to the general I/O operations also apply, such as read,write, and so on.

4.Anonymous pipe Read and write Data

Take a look at the example:

#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <    unistd.h>void write_pipe (int fd)//pipe read End {char *message= "Hello pipe test\n"; if (Write (Fd,message,strlen (message) +1))//write data to the pipe read end, use write to printf ("Write success\n");}    void read_pipe (int fd)//pipe write-end {char *message;    Message= (char *) malloc (100*sizeof (char));    if (read (fd,message,100))//read data from the pipe read {printf ("Get pipe:%s\n", message);    } else {printf ("Get Message fail\n"); } free (message);}   int main () {int fd[2];    Define a two-dimensional array of type int, as the parameter int stat_val of the pipe function;    pid_t pid;        if (pipe (FD))//Create pipe {printf ("Make a pipe fail\n");    return 0;  } pid=fork ();            Create Child process switch (PID) {case 0://Sub-process for read close (fd[1]);            Read_pipe (Fd[0]);        Exit (0);            Case-1: printf ("fork A new process fial");        Exit (0); Default://parent process used to write close (FD[0]);            Write_pipe (fd[1]);            Wait (&stat_val);    Exit (0); } return 1;}

Execution Result:

Writesuccess

Getpipe:hello Pipe Test

5. Famous pipes

As the name implies, a well-known pipeline is a pipe with names, of course, the difference between him and the anonymous pipe is that he has the name, at the same time, he also overcame some of the anonymous pipeline defects and deficiencies, such as it can be in any two of processes between

Of course can only be limited to one-way.

6. creation of famous pipelines

The functions used to create the pipe are two:mknod and Mkfifo, the two function prototypes are respectively ;

#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h>intmknod ( const char *pathname, mode_t mode, dev_t Dev);

Description:pathname refers to the creation of a well- known pipeline full file pathname, mode for the creation of a well-known pipeline pattern, the existing permissions, generally s_ififo|0666,Dev Refers to the value of the device, which depends on the type of file created

Class, which is used only when creating a device file. function call successfully reversed or 0 failed to return -1

#include <sys/types.h> #include <sys/stat.h>intmkfifo (const char *pathname, mode_t mode);

Description:pathname refers to the creation of a well- known pipeline full file pathname,mode for the creation of a well -known pipeline pattern, the existing permissions, generally s_ififo|0666

to create a named pipe using Mknod:

Umask (0), if (Mknod ("FIFO", s_ififo|0666)) {perror ("Mkfifo error!"); Exit (0);}

to create a named pipe using Mkfifo:

Umask (0), if (Mkfifo ("FIFO", s_ififo|0666)) {perror ("Mkfifo error!"); Exit (0);}

Description: When creating a pipeline, pay particular attentionto the fact that pathname must be the path to which you have read and write permissions, because pipelines are essentially special files that are created automatically when the pipeline is created and automatically deleted after the end. And about mode, must be

must be used in front of the umask decoration, the surface permission is determined by mode , but the real permissions are mode&~umask obtained. Also, a well-known pipeline in the Read and write, like a file to open, read and write closed.

7. Examples of well- known piping applications:

processread.c#include<stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/stat.h    > #include <fcntl.h> #include <sys/types.h>int main () {char buf[1024];        int FD;    Umask (0); Fd=open ("Myfifo", o_rdonly);  Open the pipe name named MyFile, and the path is the current path, read (fd,buf,1024);   <span style= "White-space:pre" ></span>//reads the contents of the pipeline printf ("read:%s\n", buf);    The contents of the output pipeline are close (FD); Exit (0);} processwrite.c#include<stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <    fcntl.h> #include <string.h> #include <stdlib.h> #include <unistd.h>int main () {int fd;    Char buf[40]= "Hello world,this message send by FIFO!";    Umask (0); if (Mkfifo ("Myfifo", S_ififo|read:hello world,this message send by FIFO! 0666)//* Famous Create Pipeline */{printf ("==-1        Te new FIFO fail!\n ");    Exit (1);        } if ((Fd=open ("Myfifo", o_wronly) ==-1)//First open the pipe file {printf ("Open fail!\n");    Exit (1); } Write (Fd,bUf,strlen (BUF) +1);    <span style= "White-space:pre" ></span>//writes information to the pipeline close (FD); Exit (0);}

Program Description:

after compiling two files, run Processwrite first , thistime, read end because of the dependence on the writing end, the secondary process will block in the terminal, open another terminal, running processread, magical results will appear ;

Read:hello world,this message send by FIFO!

8. Famous Pipeline Comprehensive application:

Many people will think that since the pipeline is one-way, then the two pipelines will not be able to achieve mutual communication ! Yes, the following example is the implementation of two processes communicating with each other:

service.c#include<stdio.h> #include <unistd.h> #include <fcntl.h> #include <sys/types.h># include<sys/stat.h> #include <stdlib.h> #include <string.h> #include <errno.h> #define Buf_    SIZE 1024#define fifo_write "Writefifo"//service-side Write pipe name # define Fifo_read "Readfifo"//service-side read pipeline name int main () {errno=0;    int wfd,rfd;    Char Buf[buf_size];    int Len;    Umask (0); if (Mkfifo (fifo_write,s_ififo|0666))//Create a named pipe {printf ("Create%s fail because:%s", Fifo_write,strerror (errno)        );    Exit (1);    } umask (0);    Wfd=open (fifo_write,o_wronly);        Open the pipe write-End if (wfd==-1) {printf ("Open%s Errno,because:%s", Fifo_write,strerror (errno));    Exit (1);   } while ((Rfd=open (fifo_read,o_rdonly)) ==-1)//Open the pipe read end {sleep (1);        If open fails, sleeps for one second, re-reads} while (1) {printf ("Service:");  Fgets (Buf,buf_size,stdin); Get the user's input Buf[strlen (BUF) -1]= ' + '; String to end With ' strncmp ' if (buf, "Quit", 4) ==0)//If the string starts with quit, exit {close (WFD);     Unlink (Fifo_write);            Disconnect Close (RFD);        Exit (0); } write (Wfd,buf,strlen (BUF));  Write something to the channel Len=read (rfd,buf,buf_size);            Get information from the channel if (len>0) {buf[len]= ' + ';        printf ("Client:%s\n", buf); }}}//client.c#include<stdio.h> #include <sys/types.h> #include <fcntl.h> #include <sys/stat.h > #include <string.h> #include <stdlib.h> #include <errno.h> #include <unistd.h> #define Buf_ SIZE 1024#define fifo_read "Writefifo"/* Client Write pipe name, here to pay special attention to the macro definition name and actual contrast/#define FIFO_WRITE "READFIFO"//client read pipe name, here also note I    NT main () {int rfd,wfd;    Char Buf[buf_size];    int Len;    errno=0;    Umask (0); if (Mkfifo (Fifo_write, s_ififo|0666))//Create a named pipe {printf ("creat FIFO%s fail,because:%s", Fifo_write, S        Trerror (errno));    Exit (1); } while ((Rfd=open (fifo_read,o_rdonly)) = =-1)//Open the pipe read end {sleep (1);     } wfd=open (Fifo_write, o_wronly);        Open the pipe write End if (wfd==-1) {printf ("Fail to open%s, because:%s", Fifo_write,strerror (errno));    Exit (-1);    } while (1) {len=read (rfd,buf,buf_size);            Read the information in the pipeline if (len>0) {buf[len]= ' Miles ';        printf ("service:%s\n", buf);        } printf ("Client:");        Fgets (Buf,buf_size,stdin);        Buf[strlen (BUF) -1]= ' + ';            if (strncmp (buf, "Quit", 4) ==0) {close (WFD); Unlink (Fifo_write);        Disconnect Close (RFD);//close File exit (0); } write (Wfd,buf,strlen (BUF));//Write Data}}

Program Description:

once compiled separately, run the service first, thenopen another terminal to run the client, and then you can communicate with each other.


Copyright NOTICE: This article for Bo Master original article, can not be reproduced by Bo Master, but must indicate the source, I will retain the right to hold responsibility.

The pipeline of inter-process communication between Linux

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.