The inter-process communication pipe (with a hose thinking to understand)

Nothing is ever a setback. If anghing, it just motivate you for what is next .-------- no setback at all, if he has any sense, it is just inspire you again next challenge to perform better .

1, the prospects Review

Communication between processes is certainly related to the process, before the black folks who have written blog, or are interested in this area of ​​knowledge that students can a little rusty venue:

https://blog.csdn.net/weixin_46027505/article/details/104812719

https://blog.csdn.net/weixin_46027505/article/details/105141592

2, pipe really is pipeline

  • It is necessary to look at three kinds of communication before the introduction pipe.

1, 单工通信:传输方向只有一个方向,单工通信只有一根数据线,它也只在一个方向上进行,如打印机、电视机等。for example: television, radio
2, 半双工通信:可以双向通信,但只能轮流传输,也只有一根数据线,不同于单工通信的是这根数据线即可作为发送又可作为接收,虽数据可在两个方向上传送,但通信双方不能同时收发数据。such as: walkie-talkie
3, 全双工通信:可以同时双向传输数据,数据的发送和接收用两根不同的数据线,通信双方在同一时刻都能进行发送和接收,发送和接收同时进行,没有延迟。such as video chat

2.1 Pipeline popular understanding

  • Why is this communication mechanism called the pipeline it? Because its function really is the role of life in the pipe (waterway) is.

We put water supplier compared to a process space, our own home is another process space, the pipeline is used to bottled water, water is the data transmission process communication between us, the water in the pipes is equivalent to write data to a file
where required Remember, the pipeline is one-way, FIFO , this is easy to understand, just as water suppliers to give you bottled water, you can not inject water into the pipes.

2.2 Why pipeline is half-duplex communication?

Because of a Linux command can only perform one function, it is a more complex task requires several collaborative process is completed, the results need to deal with the first process to the second process, and then handed over to a third, and so on, like assembly line Like a complete commodity production, this process takes only one-way transmission of data down, so the design of the time made a half-duplex.
Course also be used to achieve duplex communication pipes, two pipes.

2.3 Pipeline Features

Conduit is connected to which input and output of a process to another process.

1, a process (writing process) to write data at the end of the pipeline, another process (read process) of reading data from the head pipe.
The pipe end is fixed to read and write ends. Write the contents of each buffer are added at the end of the pipe, and each time data is read from the head of the buffer.

2, the data is read out after a process, will be removed from the pipeline, the other reading process will not be able to read the data.

3, the pipeline provides a simple flow control mechanisms, the process of trying to read an empty pipeline, the process will be blocked. Similarly, the pipeline is already full, and then attempt to write data to the process piping, process will be blocked

4, both ends of the conduit pipe for the process, is a file, but it is not a common file, it does not belong to a certain file system, but live on their own, constitute a single file system, and only exists in memory.

5, data is written to the pipeline, linux will not guarantee atomicity written, there is a free area of ​​the pipe buffer, the writing process will attempt to write data to the pipe. If the reading process does not go read data pipeline buffer, the write operation will block.

6, only when there is a read end of the pipe, it makes sense to write data to the pipe. Otherwise, the process of writing data to the pipeline will receive kernel came SIFPIPE signal, the application can process the signal, can be ignored (the default action is to terminate the application).

  • Of course, there are two types of pipes.
    1, unnamed pipes : The only be used for the parent and child, and that you can be understood, the separation of you and your dad, this is for you two pipes of water supply. Because the pipeline you and Daddy
    2, Named Pipes : can be used in the same system, any inter-process communication.

Back immediately introduced to.

3, unnamed pipes (sometimes called a direct pipeline, not to be confused)

Pipeline is the oldest form of UNIX System IPC, all UNIX systems provide such a communication mechanism. Essence conduit is a kernel buffer to process FIFO (FIFO, First In First Out) buffer to access data from manner: one end of the pipeline process is sequentially written to the buffer to process the data, and the other end of the process sequentially reads the data, which can be seen as a circular queue buffer, the read and write locations are automatically added, data can only be read once and then read the buffer are gone. When the buffer is empty or filled with reading, there are certain rules to control the corresponding read or write process whether the process enters a wait queue, when the buffer is empty new data is written or slow data read out of the buffer, waiting to wake up the queue process continues to read and write.

3.1 Limitations

(1) half-duplex, data can only flow in one direction, now some systems may support full-duplex pipes, but for optimum portability, should consider the system does not support full duplex pipe;

(2) it can only be used with pipes unnamed parent-child relationship between the communication process;

# 3 create 3.2 unnamed pipe
pipeline can be viewed as a special kind of file, for it to read and write can also use ordinary read, write and other functions. But it is not a regular file, it does not belong to any other file system, and exists only in memory.
Pipeline by calling pipe function creates.

#include <unistd.h>
int pipe(int fd[2]); 
  • Return Value: If successful, returns 0, if the error, return -1.
    Two file descriptor returned via the parameter FD:
    FD [0] is opened for reading only (used in water pipes)
    FD [. 1] only opened for writing (used in water pipes)
    FD output [1] is fd [0] input

4, single-process communication pipe unknown

In fact, the pipeline is file, the following sample code is for ourselves and send a message read out.
Here Insert Picture Description

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>


#define MSG "my name is xuxiaohei"

int main(int argc, char **argv)
{
    int     pipe_fd[1];
    int     rv;
    char    buf[512];


   
    if (pipe(pipe_fd) < 0)
    {
        printf("Create pipe failure: %s\n", strerror(errno));
        return -1;
    }

    memset(buf, 0, sizeof(buf));
        
    if (write(pipe_fd[1], MSG, strlen(MSG)) < 0)
    {
        printf(" write data to pipe failure: %s\n", strerror(errno));
        return -2;
    }
    
    rv = read(pipe_fd[0], buf, sizeof(buf));
    if (rv < 0)
    {
            printf(" read from pipe failure: %s\n", strerror(errno));
            return -3;
    }
    printf("process read %d bytes data from pipe: \"%s\"\n", rv, buf);

      

    return 0;
}

Here Insert Picture Description

5, to achieve a parent and child communication unnamed pipes

The following write a routine to send data to the parent process child process direction. First, the parent process created after the pipeline fork (), then the child will inherit the parent of all open file descriptors (including pipelines), then there are four for a pipeline to read and write end (parent and child have a pair of pipes to read and write end), if you need the parent process to write data to the child inside, you need to close the read end of the parent process, close the write end in the child; and if required the child to write data to the parent, you can turn off the parent process write terminal, and then the child process close the read end.
Here Insert Picture Description

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>

#define MSG_STR "This message is from father: Hello, my son!"

int main(int argc, char **argv)
{
    int     pipe_fd[1];
    int     rv;
    int     pid;
    char    buf[512];
    int     wstatus;

    printf("before creat pipe\n");
    if (pipe(pipe_fd) < 0)
    {
        printf("Create pipe failure: %s\n", strerror(errno));
        return -1;
    }


    printf("before fork\n");
    if ((pid = fork()) < 0)
    {
        printf("Create child process failure: %s\n", strerror(errno));
        return -2;
    }
    else if (pid == 0)
    {
        printf("son start read message from father\n");
        close(pipe_fd[1]);
        memset(buf, 0, sizeof(buf));
        rv = read(pipe_fd[0], buf, sizeof(buf));
        if (rv < 0)
        {
            printf("Child process read from pipe failure: %s\n", strerror(errno));
            return -3;
        }
        printf("Child process read %d bytes data from pipe: \"%s\"\n", rv, buf);
        return 0;
    }




    close(pipe_fd[0]);
    if (write(pipe_fd[1], MSG_STR, strlen(MSG_STR)) < 0)
    {
        printf("Parent process write data to pipe failure: %s\n", strerror(errno));
        return -3;
    }


    printf("father finish write and wait son read \n");
    wait(&wstatus);


    return 0;
}

Closing one end of the pipe     
(1) When reading a write pipe end is closed, after all the data is read, read returns 0, indicating the end of the file;     
(2) when a read write pipe ends are closed, the SIGPIPE generating a signal, if the signal is ignored or catch and the return signal from the handler, wirte -1.

Here Insert Picture Description

If you want to send a message to the child process the parent process
is
Here Insert Picture Description

6, named pipes FIFO (or called named pipes)

Of course, the same named pipe is half-duplex.

Not mentioned in front of named pipes between two processes only be more related to communication,
through named pipes (Named PiPe) FIFO, unrelated processes can exchange data.

It provides a pathname associated, in the form of a FIFO file exists in the file system. Thus, even if the FIFO process creating process genetic relationship does not exist, as long as access to the path, it is possible via a communication (between processes can access the path and the process of creating the FIFO) FIFO each other, on the disk that has a corresponding nodes, but not block - in other words, just have a name and the appropriate access rights, by mknode () system call or mkfifo () function to create. Once established, any process can open it and read and write by file name, but not limited to parent and child, of course, the premise is the process of FIFO have appropriate access rights. When the process is no longer used, FIFO release in memory, but the disk nodes remain.

Therefore, the FIFO unrelated processes can exchange data. It is noteworthy that, strictly follow the FIFO FIFO (first in first out), read and FIFO pipeline always return data from the beginning, adding to write data to put them to the end. They do not support, such as lseek () and other documents positioning operation.

7, the difference between anonymous pipes and named pipes

The biggest difference between the two is :

有名在任意两个进程间可以通信
无名只能在父子进程间通信

Also named pipe on black writing a blog implement a small application.

Published 29 original articles · won praise 65 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_46027505/article/details/105151719