[Linux] - inter-process communication advantages and disadvantages

1, pipeline

1.1 anonymous pipes

Mainly used for inter-process communication, that are related

Let's look at a Linux statement:

test1 | grep 8080

If you had not named Linux, you must know "|" means, in fact it is the conduit means, his role is to input a command output as the previous command.

The above code is actually output as grep 8080 test1 enter this command, where "|" is actually an anonymous pipe, can only be used with a communication kinship process.

If two processes need to communicate, then you have to create two pipes. Because this communication is one way of the following examples are on anonymous pipes:

In the process, we have created a pipeline, the parent closed the write channel, child closes the read channel, the child process writes the string to the pipeline, the parent process and read the string output into the pipeline.

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#define MAX_LEN 128
int main(void)
{
    /*0为读,1为写*/
    int fd[2] = {0}; //描述符
    pid_t pid = 0;
    char line[MAX_LEN] = {0};
    int n = 0;

    /*创建管道,需要传入两个文件描述符*/
    if(pipe(fd) < 0)
    {
        perror("create pipe failed\n");
        return -1;
    }
    /*fork子进程*/
    if((pid = fork()) < 0)
    {
        perror("fork failed\n");
        return -1;
    }
    /*父进程*/
    else if(pid > 0)
    {
        /*关闭管道的写描述符*/
        close(fd[1]);

        /*从管道读取数据*/
        n = read(fd[0],line,MAX_LEN);
        printf("read %d bytes from pipe :%s\n",n,line);

    }
    /*子进程*/
    else
    {
        /*关闭管道的读描述符*/
        close(fd[0]);
        /*向管道写入数据*/
        write(fd[1],"test",sizeof("test"));
    }
    return 0;
}

1.2, named pipes

Named pipes can be used for any inter-process communication.

The following is to create a named pipe methods:

mkfifo test

This command creates a pipeline named test, then we write data to the pipe with a process, then another process writes data readout:

echo “this is a pipe” >test 

If the pipeline data is not read out, that it will wait until there are other processes by the data read-out:

cat < test  //读数据

Only the data is read by another process, the end of the write data on a considered.
Here also reflects the shortcomings of the pipeline - inefficient, I'll give you transfer data, but only the data you away, I was able to return, this is very slow, the process is not suitable for frequent communication. But it also has an advantage that can ensure you really get my data.

The following is an example of the complete code named pipe on:

We first create a named pipe, if successful, the closed end of his reading, writing data to the inside.

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#define FIFO "/tmp/fifo"
#define MAX_LEN 128
int main(void)
{
    int writeFd;
    char line[MAX_LEN] = {0};
    if(mkfifo(FIFO,S_IRUSR|S_IWUSR) < 0 && (errno != EEXIST))
    {
         perror("make fifo failed:");
         return -1;
    }
    /*关闭管道的读描述符*/
    writeFd = open(FIFO,O_WRONLY,0);
    /*向管道写入数据*/
    write(writeFd,"www.yanbinghu.com",sizeof("www.yanbinghu.com"));
    close(writeFd);
    return 0;
}

Then the new terminal opens a named pipe just created, data is read from the inside:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include<fcntl.h>
#define FIFO "/tmp/fifo"
#define MAX_LEN 128
int main(void)
{
    int readFd,n;
    char line[MAX_LEN] = {0};
    /*打开FIFO,这里打开可能失败,应该要对返回值处理*/
    readFd = open(FIFO,O_RDONLY,0);
    /*从FIFO读取数据*/

    n = read(readFd,line,MAX_LEN);
    printf("read %d bytes from pipe :%s\n",n,line);
    close(readFd);
    /*删除FIFO*/
    unlink(FIFO);
    return 0;
}

Then run the process of writing and reading process, so two unrelated processes can communicate through anonymous pipe.

to sum up:

  • Half-duplex, that is not capable of simultaneous transmission of data in both directions, some systems may support full-duplex.
  • Anonymous pipes can only be used, that are related communication process
  • Named pipes can be used for any inter-process communication

2, the message queue

Learn more pipelines we know, a write data to b, b-only data read-out, a return to order, then we can not but wait, I put the data to you, and then I immediately returned it?

Actually possible, a message queue can solve such a problem, as long as the data A into the message queue b, which can be a, b use data extracted directly from the message queue.

  • Disadvantage: if a data sent is too large to b, and the communication frequency, then the message queue is inappropriate, because the data is too large, a long time of transmitting data, to copy the data b takes a long time, efficiency is low .
  • Advantages: Once the pipeline related process exits, that there will be no data, but not the same message queue, a process which the data is written to the exit, another process can still take data.

3, shared memory

Message queue for the shortcomings, the shared memory allows multiple processes to share a given memory area, because they are a shared data memory, the memory copy time is reduced, and therefore very fast .

But here we might ask: each process is not independent of it? How can a shared memory?

In fact, the system loads a process, not the memory allocated to the process of actual physical memory, virtual memory space but we can make two processes each take a piece of virtual address space, and then mapped to the same physical memory, Although this process has two independent virtual address space, but there is a part of the same physical memory mapping, thus completing the memory sharing mechanism, as shown below:
Here Insert Picture Description
Cons: multi-process memory competition, similar to what we usually say thread Safety.

4, the semaphore

Summarized in one sentence: the nature of the semaphore is a counter for synchronization and mutual exclusion between processes.

For example semaphore initial value of 1, and then a process to access the shared memory, we put the value of the semaphore is set to 0, then b process to access the shared memory, to see the semaphore is 0, you know it has been used to access the memory, and that it can not visit the b. So a means of communication between the semaphore is a process.

5、Socket

Above we mentioned pipes, message queues, shared memory and semaphores are communications between the same host, how those two processes thousands of miles apart to communicate it?

Socket answer is, for example, usually we launched an http request through the browser and the server returns the corresponding data to you, this is the use of Socket communication, that is to say: it can be used between different processes between different computers Communication.

to sum up

  • For the pipeline : slow, the last reference to it when the process terminates, leaving in the pipeline data will be deleted. Anonymous pipes used in the process of genetic relationship, named pipes for interprocess communication in any key. Half-duplex communication, a write data, a read data can only be one-way.
  • Message Queuing : kernel priority queue, a plurality of processes to communicate with a node placed in a queue, or queue node acquires
  • Shared memory : each process by mapping the same physical address for communication, reducing the memory copy time. But pay attention to safety multi-process communication
  • Semaphore : situation detected by the memory access counter, if the process has access to the memory, the count becomes 0, there is no process to access, counts the count becomes 1. The two states only 0/1.
  • Socket used for communication between different computers in different processes, it is among the most widely used in the process of communication.
Published 42 original articles · won praise 13 · views 1763

Guess you like

Origin blog.csdn.net/Vicky_Cr/article/details/105294303
Recommended