Linux multiprocess programming three -- process communication

Keywords: Linux

1, Process communication foundation

1. What is process communication

A process is an independent resource allocation unit. Resources between different processes (processes mentioned here usually refer to user processes) are independent and have no association. Resources of another process cannot be accessed directly in one process. However, processes are not isolated. Different processes need information interaction and state transmission, so Inter Processes Communication (IPC) is required.

Purpose of interprocess communication:

1. Data transmission: one process needs to send its data to another process

2. Notification event: a process needs to send a message to another process or group of processes to notify them of something (for example, the parent process needs to be notified when the child process terminates)

3. Resource sharing: multiple processes share the same resources.

4. Process control: some processes want to fully control the operation of another process (such as DEBUG). At this time, the control process wants to be able to intercept all traps and exceptions of another process.

2. Classification of interprocess communication modes

 

2, Pipeline communication

1. Anonymous pipeline communication

1. Concept

Pipe is also called anonymous pipe. It is the oldest form of IPC (interprocess communication) in UNIX system. All UNIX systems support this communication mechanism. The command to count the number of files in a directory: ls | wc – l. in order to execute this command, the shell creates two processes to execute ls and wc respectively.

 

2. (anonymous) pipeline characteristics

1. The pipeline is actually a buffer maintained in the kernel memory. The storage capacity of this buffer is limited, and the size of different operating systems is not necessarily the same.

 

2. Pipelines have the characteristics of files: read and write operations. Anonymous pipelines have no file entities, and famous pipelines have file entities, but do not store data. The pipeline can be operated in the way of operating files.

3. A pipeline is a byte stream. When using the pipeline, there is no concept of message or message boundary. The process reading data from the pipeline can read data blocks of any size, regardless of the size of the data blocks written to the pipeline by the writing process.

4. The data transmitted through the pipeline is sequential. The order of bytes read from the pipeline is exactly the same as the order in which they are written to the pipeline.

5. The transmission direction of data in the pipeline is unidirectional. One end is used for writing and the other end is used for reading. The pipeline is half duplex.

6. Reading data from the pipeline is a one-time operation. Once the data is read, it will be discarded from the pipeline to free up space for writing more data. lseek() cannot be used to randomly access data in the pipeline.

7. Anonymous pipes can only be used between processes with common ancestors (parent and child processes, or two brother processes, which are related).

8. The data structure of the pipeline is a logical ring queue, which is operated by read pointer and write pointer

 

 

3. Anonymous pipeline related instructions and anonymous pipeline creation

ulimit -a//View pipeline buffer size command
long fpathconf(int fd, int name); //View pipeline buffer size function
//name Is an optional macro parameter
_PC_PIPE_BUF //View buffer size for

 

 

  Here, the buffer size is 8 blocks of 512 bytes, a total of 4096 bytes.

Create anonymous pipe

/*

        #include <unistd.h>
        int pipe(int pipefd[2]);
        Function: create an anonymous pipe for inter process communication,
        Parameters:
            int pipefd[]The array is an outgoing parameter (i.e. function storage) and holds two file descriptors
                pipefd[0]Corresponding pipe reading end
                pipefd[1]Corresponding pipe write end
        Return value:
            -Success: 0
            -Failed: - 1
        #########Anonymous pipes can only communicate in related processes
        #########The pipeline is blocked by default. If the pipeline has no data, read is blocked. If the pipeline is full, write is blocked
*/

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

//The child process sends data to the parent process, and the parent process reads the data for output
int main(){
    //Create a pipe before the parent-child process is created
    int pipefd[2];
    int pipefd1[2];
    int ret = pipe(pipefd);
    int ret1 = pipe(pipefd1);
    if(ret==-1||ret1==-1){
        perror("pipe");
        exit(0);
    }
    pid_t pid;
    pid = fork();
    //Parent process
    if(pid>0){
        printf("i am parent pid:%d\n", getpid());
        char buf[1024] = {0};
        while(1){
            //The parent process reads from pipeline 1 and writes from pipeline 2
            int len = read(pipefd[0], buf, sizeof(buf));
            printf("parent recive : %s, pid:%d\n", buf, getpid());
            
            char * str = "hello, i am parent";
            write(pipefd1[1], str, strlen(str));
            sleep(1);
        }
    }
    //Subprocess
    else if(pid==0){
        printf("i am child pid:%d\n", getpid());
        char buf[1024] = {0};
        while(1){
            //Subprocess pipeline 1 writes, pipeline 2 reads
            char * str = "hello, i am child";
            write(pipefd[1], str, strlen(str));
            sleep(1);
            int len = read(pipefd1[0], buf, sizeof(buf));
            printf("child recive : %s, pid:%d\n", buf, getpid());
        }
        
    }
    return 0;

}

4. Anonymous pipeline reading and writing features

Pay attention when using pipes (assuming that they are in I/O blocking operation)

1. All write ends are closed (the reference count of the write end of the pipeline is 0). If a process reads data from the read end of the pipeline, the remaining data in the pipeline will return 0 after being read again, as if it had been read to the end

2. If the write end is not fully closed (the reference count of the pipeline write end is greater than 0), and the process holding the pipeline write end does not write data to the pipeline, a process reads data from the pipeline and will be blocked until the write end writes data

3. If the readers are closed (the reference count of the pipeline reader is 0), and a process writes data to the pipeline, the process will receive the signal SIGPIPE, which usually leads to the abnormal termination of the process

4. If the reader is not fully closed (the reference count of the pipeline reader is greater than 0), the write data will be blocked until the reader reads the data

Summary:
Read:
There is data in the pipeline: read the data actually read
No data in pipeline:
All write ends are closed, and read returns 0
The write side is not closed, the read is blocked and waiting
Write:
When the pipeline reader is completely closed, the process will terminate abnormally (the process receives SIGPIPE signal)
The reading end of the pipeline is not fully closed:
The pipe is full and blocked
Pipeline is not full, write

   

Posted by arsitek on Sat, 04 Dec 2021 16:39:28 -0800