Inter-process communication (I)-pipelines and inter-process communication Pipelines

Source: Internet
Author: User

Inter-process communication (I)-pipelines and inter-process communication Pipelines

I will use several blogs to summarize several methods of communication between processes in Linux. I will write the summary at the beginning in each blog of this series.

Communication between processes

  • MPs queue
  • Message Queue
  • Signal
  • Semaphores
  • Shared storage Zone
  • Socket)

In a Linux system where everything is file, the MPs queue is also a file (special file). You can use the mkfifo command to create an MPS queue file.

 

There is a p in front of the MPs queue file to identify the MPs queue file.

 

This time, we mainly talk about the communication between processes through pipelines. There are two ways to communicate through pipelines.

One is anonymous pipeline and the other is named pipeline.

 

  • Anonymous Pipeline


Let's take a look at a piece of code.

 

1 # define MAXLINE 80 2 int main () 3 {4 int n; 5 int fd [2]; 6 pid_t pid; 7 char line [MAXLINE]; 8 if (pipe (fd) <0) 9 perror ("pipe"); 10 if (pid = fork () <0) 11 perror ("fork "); 12 if (pid> 0) 13 {14 // father15Close (fd [0]);16} 17 else18 {19Close (fd [1]);20 n = read (fd [0], line, MAXLINE); 21 write (stdout, line, n); // write it to the standard output to see the effect 22} 23 return 0; 24 25}

This program is an example of a simple communication between parent and child processes through pipelines. The specific work process is shown by drawing.

 

Note that this step is very important. If the corresponding port is not closed, the pipeline cannot be operated correctly.

The anonymous pipeline is mainly used. When a child process is created, the file descriptor table of the parent process is copied to this feature, the Parent and Child processes see a public resource-pipeline and have the right to diarrhea in the pipeline. Then, one party reads and one party writes to complete communication between processes.

The so-called anonymous pipeline means that there is no name... You do not know where the MPs queue file is stored or the file name of the MPs queue file. The only object that is associated with the MPs queue file is the file descriptor in the parent-child process. According to the implementation mechanism of the anonymous pipeline, it is easy to see its advantages and disadvantages.

 

  • N features of Pipelines
    • Pipelines depend on the file system. After creating pipelines, you must disable unused read/write ends.
    • Only parent-child processes can communicate with each other using MPs queues. (Exclusive to anonymous pipelines)
    • Pipelines are based on data streams and are oriented to byte streams! (The message queue is designed for data blocks, which is easier to understand)
    • Pipelines can only be called one-way data communication, and even half-duplex data cannot be considered
    • The synchronization and mutex issues do not need to be considered. The pipeline has already considered
    • When the Parent and Child processes exit, the lifecycle of the MPs queue ends, that is, the lifecycle of the MPs queue is the process.

The above is the use and implementation mechanism of the anonymous pipeline. It can be seen that the anonymous pipeline can be used to complete inter-process communication only when there must be a "kinship" between processes. Of course, the Parent and Child processes are acceptable ~

 

In order to solve the problem that only a process with kinship can use this method for communication, a communication method named pipe is available.

  • Named Pipe

Simply put, the anonymous pipeline we just used is used because we do not know the file name and storage path. Therefore, we can only inherit the file descriptor table to obtain the method for establishing a connection with the anonymous pipeline, what if we know the path and MPs queue file name? Can we complete non-kinship process communication?

  • Function prototype int mkfifo (const char * pathname, mode_t mode)
  • The first parameter pathname is the path, and mode is the access permission of the created pipeline umask
  • Header file: # include <sys. stat. h> # include <sys/types. h>
  • Return Value. 0 is returned for success, and-1 is returned for failure.

Paste the code below

 This is the server's

    1 #include <sys/types.h>                                                 2 #include <sys/stat.h>                                                  3 #include <stdio.h>                                                     4 #include <unistd.h>                                                    5 #include <stdlib.h>                                                    6 #include <errno.h>                                                     7 #include <string.h>                                                    8 #include <fcntl.h>                                                     9 #define _PATH_NAME_ "./pp"                                            10                                                                       11 int main()                                                            12 {                                                                  >> 13   char *str="hello world";                                            14   int fd;                                                             15   if(mkfifo(_PATH_NAME_,0644)<0)·                                     16   {                                                                   17     printf("hahaha\n");                                               18     printf("mkfifo error %d:%s\n",errno,strerror(errno));             19   }                                                                   20   fd=open(_PATH_NAME_,O_WRONLY);                                      21   write(fd,str,strlen(str));                                          22   return 0;                                                           23 }                                                                  

This is the client's

  2 #include <sys/types.h>  3 #include <sys/stat.h>  4 #include <stdio.h>  5 #include <unistd.h>  6 #include <stdlib.h>  7 #include <errno.h>  8 #include <string.h>  9 #include <fcntl.h> 10     11 #define _PATH_NAME_ "./pp" 12     13     14 int main() 15 {   16   int fd; 17   fd=open(_PATH_NAME_,O_RDONLY);                                      18   char buf[1024]={'\0'}; 19   read(fd,buf,1024); 20   printf("%s\n",buf); 21   return 0; 22 }  

You can use the open function to open the read and write Functions to read and write pipelines respectively. Of course, you can also close the standard input and output to achieve redirection.

 

How big is the pipeline? How much data can we throw into it?

Since the MPs queue is also a file, there must be an upper limit on the size, which is also a disadvantage and limited in size.How much data can be written into the pipeline? Run the man 7 pipe command to open the pipe instruction document.

Pipe capacity
A pipe has a limited capacity. If the pipe is full, then a write (2)
Will block or fail, depending on whether the O_NONBLOCK flag is set
(See below). Different implementations have different limits for
Pipe capacity. Applications shocould not rely on a special capacity:
An application shoshould be designed so that a reading process consumes
Data as soon as it is available, so that a writing process does not
Remain blocked.

In Linux versions before 2.6.11, the capacity of a pipe was the same
The system page size (e.g., 4096 bytes on i386). Since Linux 2.6.11,
The pipe capacity is 65536 bytes.

See, my current version is later than 2.6.11, so it is 65536 bytes, and the version is 4096 bytes.

 

Finally, comeThe biggest disadvantage of an MPS queue is that it is based on a file system! Therefore, whether it is read or write, you need to access the disk for I/O operations. You know the I/O speed., Especially slow, so it is not suitable for the structure of multiple clients, otherwise it will be slow

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.