[Linux] Interprocess communication (anonymous pipes, named pipes, shared memory)

introduction

The essence of communication is to transfer data, which is mutual.
Processes cannot directly transfer data to each other. Processes are independent. All data operations will have copy-on-write, which must be communicated through an intermediate medium.
The essence of inter-process communication: let different processes see the same resource (memory space) first.

process communication

Purpose:
Data transfer: One process needs to send its data to another process.
Resource sharing: The same resources are shared among multiple processes.
Notification events: A process needs to send a message to another or a group of processes to notify it (them) that some event has occurred (such as to notify the parent process when a process terminates).
Process control: Some processes want to completely control the execution of another process, and the controlling process hopes to intercept all traps and exceptions of another process, and be able to know its state changes in time.

Interprocess communication development

1. Pipes
2. System V inter-process communication
3. POSIX inter-process communication

Interprocess Communication Classification

Pipes:
1. Anonymous pipe
2. Named pipe

System V IPC
1.System V message memory
2.System V shared memory
3.System V semaphore

POSIX IPC
1. Message queue
2. Shared memory
3. Semaphore
4. Mutex
5. Condition variable
6. Read-write lock

pipeline

insert image description here

anonymous pipe

Provides inter-process communication for processes that are related by blood. (Common in parent-child)
Pipes can only communicate data in one direction.
Therefore, the parent and child processes close unnecessary file descriptors to achieve the purpose of building a one-way communication channel.
insert image description here

Why ever have to open?
If you do not open reading and writing, the file obtained by the child process must be opened in the same way as the parent process and cannot communicate.

Build pipeline code:

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

int main()
{
    
    
	int pipe_fd[2] = {
    
    0};
	if(pipe(pipe_fd) < 0)
	{
    
    
		perror("pipe");
		return 1;
	}
	printf("%d", %d\n",pipe_fd[0],pipe_fd[1]);
	pid_t id = fork();
	if(id<0)
	{
    
    
		perror("fork");
		return 2;
	}
	else if(id == 0)
	{
    
    
	//关闭读
		close(pipe_fd[0]);

		const char *msg = "hello parent ,i am child";
        int count =5;
		while(count)
		{
    
    
			write(pipe_fd[1],msg,strlen(msg));
			sleep(1);
			count--;
		}
		close(pipe_fd[1]);
		exit(0);
	}
	else
	{
    
    
	//关闭写
		close(pipe_fd[1]);
        
        char buffer[64];
        while(1)
        {
    
    
        	buffer[0] = 0;
        	ssize_t size = read(pipe_fd[0],buffer,sizeof(buffer) - 1);
        	if(size>0)
        	{
    
    
        		buffer[size] = 0;
        		printf("parent get message from child# %s\n",buffer);
        	}
        	else if(size == 0)
        	{
    
    
        		printf("pipe file close,child quit!\n");
        		break;
        	}
        	else
        	{
    
    
        		 //...........
        	}
        }  
        int status = 0;
        if(waitpid(id,&status,0)>0)
        {
    
    
        	printf("child quit,wait success!\n");
        }
        close(pipe_fd[0]);
	}
	return 0;
}

Inter-process synchronization:
If there is no message in the pipe, the parent process (reader) is waiting, waiting for the data inside the pipe to be ready (the child process writes).
If the write end of the pipe is full. Continuing to write cannot be written, it is waiting, waiting for free space inside the pipe (the parent process reads it away).
The pipe itself is a file.

Features of the pipeline:
1. The pipeline has its own synchronization mechanism!
2. The pipeline is one-way communication!
3. The pipeline is byte-oriented!
4. Pipes can only guarantee communication between processes with blood relationship, and are often used in parent-child processes.
5. The tube can guarantee a certain degree of atomicity of data reading!

The process exits, and the files that were once opened are also closed. Pipes are also files, and the life cycle of pipes depends on the process!

Read off, keep writing, meaningless. The essence is to waste system resources, and the writing process will be immediately terminated by the OS!
![Insert image description here](https://img-blog.csdnimg.cn/24f1b7304f6c418aa3445425893aae67.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBATGF5bWFu5YWJ772e,size_20,sex_FFFFFF,t_70,g

named pipe

Interprocess communication between unrelated processes is called named pipes.
Anonymous pipes: the characteristics of parent-child sharing of files
Named pipes: The file path is unique, allowing processes to see the same file

Shared memory

The essence of inter-process communication: let different processes see the same resource first!
1. The OS applies for a piece of physical memory space
2. The OS maps the memory into the shared area of ​​the corresponding process (between stacks)
3. The OS can return the mapped virtual address to the user

1. Apply for shared memory
2. Process 1 and process 2 respectively attach the corresponding shared memory to their own address space (shared area)
3. Both parties see the same resource! That's it for normal communication!

The (IPC) ipc module that provides the communication mechanism inside the operating system

View shared memory: ipcs -m
All ipc resources are with the kernel, not with the process.
Delete shared memory: ipcrm -m shmid number

//创建key
key_t k = ftok(PATH_NAME,PROJ_ID);
//申请共享内存
int shmid = shmget(k,SIZE,IPC_CREAT|IPC_EXCL);//共享内存如果不存在,创建;如果存在,出错返回。
//释放共享内存
shmctl(shmid,IPC_RMID,NULL);
//将当前进程和共享内存进行关联
char* start = (char*)shmat(shmid,NULL,0);
//将当前进程和共享内存去关联
shmdt(start);

1. The life cycle of shared memory varies with the OS
2. Shared memory does not provide any synchronization and mutual exclusion operations, both parties are independent of each other
3. Shared memory is the fastest among all inter-process communication

Shared memory size: When the system allocates shm, it is based on 4kb.

key: is a unique key value generated by the user layer. The core function is to distinguish "uniqueness" and cannot be used to operate IPC resources!
shmid: It is the IPC resource identifier returned by a system to us, which is used to operate the IPC resource.

Analogy:
key, inode number
shmid of the file, fd of the file

Signal amount

1. Let the process see the same resource (memory space), this resource is called critical resource.
2. All the code in the process, not all the code is accessing critical resources, but only a part is accessing. It is this small amount of code that may cause the data inconsistency problem. (Critical section code)
3. In order to avoid data inconsistency and protect critical resources, some protection of critical section code is required. (The method is called mutual exclusion)
4. Mutual exclusion: a part of the space can be accessed by one and only one process at any time. Serialized execution (lock, binary semaphore)
5. There are corresponding codes for locking and unlocking. Essence: lock and unlock the critical section to complete the mutual exclusion operation.

Semaphore: Essentially a counter. (counter used to describe the number of resources in critical resources)
Apply for semaphore: P operation (counter subtraction)
Release semaphore: V operation (counter addition)

Pseudocode for PV operation:

P:
begin:
Lock();
	if(count<=0)
	{
    
    
		goto begin;
	}
	else
	{
    
    
		count--;
	}
	Unlock();

//内部访问临界资源。

V:
Lock();
count++;
Unlock();

1. Multiple processes cannot operate on the same count value
2. Semaphore is the safety of protecting critical resources

The semaphore itself is a critical resource.

1. Semaphore, in a multi-process environment, how to ensure that the semaphore is seen by multiple processes?
semget, semctl, ftok() ---->Key ----->IPC
2. If the value of the counter of the semaphore is: 1
, it is 1, 0 two kinds of results, binary semaphore ----> It is a kind of mutual exclusion semantics.

Guess you like

Origin blog.csdn.net/qq_46994783/article/details/123373079