Process communication shared memory

1, Shared memory

Shared memory is that the operating system directly opens up a space on the physical memory as a buffer area for inter process communication. Compared with other process communication methods such as pipeline and message queue, shared memory has higher efficiency because the design of shared memory is based on the address of physical memory, This saves a lot of system calls compared with other methods of IPC, so it improves its efficiency to a great extent.

2, Principle of shared memory

When the virtual address space of different processes is loaded into the memory according to the size of the page, the virtual address sent by the CPU can get the corresponding physical address after the address conversion of the MMU (memory management unit), and then a series of operations such as memory access can be carried out, The shared memory API is to load a part of the virtual address space of different processes, and then map it to the same physical memory. In this way, different processes can access the same physical memory, so as to carry out process communication between different processes. It should be noted that since the physical memory used for process communication becomes a critical area at this time, race conditions may occur when different processes access. Therefore, in order to realize process synchronization, mutual exclusion and simultaneous operation must be realized for different processes when accessing the temporary area. This is very important. I hope we can pay attention to it.

3, Shared memory API analysis

shm:share memory Abbreviation for shared memory
1.shmget
 Function prototype: int shmget(key_t key, size_t size, int shmflg);
Function function: create new or existing shared memory.
parameter key:key Value, which is the same as that required by message queuing key Is the same, how to get?
See:(https://blog.csdn.net/ASJBFJSB/article/details/104122200)
(1)If key Value has no corresponding shared memory. To create a new shared memory, the creation process is essentially os In physical memory
 An area is divided on the as the storage space to contribute memory.
(2)If key The value has been determined, indicating that there is already a shared memory, which is created by other processes before. At this time shmget Is to get
 Should key Corresponding shared memory.

parameter size:Specifies the size of shared memory, which is generally an integer multiple of the page size(4k),If not, for the convenience of mapping and memory
 Administration, api Will automatically size Adjust to an integer multiple of the page size.

parameter shmflg:Specify permissions and IPC_CREAT. 

Return value:
Success: returns the unique identifier of the shared memory.
Failed: Return-1. 
2.shmat
 Function prototype: void *shmat(int shmid, const void *shmaddr, int shmflg);

Function: will shmid The shared memory space pointed to is mapped to the virtual address space of the current process,
And return the mapped starting address. If you get this address, you can read and write on it.

parameter shmid: shmid By shmget Gets a unique identifier that identifies the shared memory.
parameter shmaddr: Specifies the starting address of the mapping.
(1)Set the starting address of the mapping yourself (the address of the virtual address space). It is recommended not to use it, because you don't understand it in the virtual address space
 Where used, where may not have been used.
(2)pass NULL,The mapped address is filled in by the operating system. Because only os Just know where to map and where not to map.
parameter shmflg: Specify the mapping criteria.
(1)0: The shared memory is mapped in a readable and writable manner.
(2)SHM_RDONLY: Map as read-only.

Return value:
Success: return mapping address
 Failed: Return(void*)-1
3.shmdt
 Function prototype: int shmdt(const void *shmaddr);
Function: disconnect the current process virtual address space from shmaddr Mapping to shared memory.
parameter shmaddr: Pointer to shared memory
 It should be noted that shmdt The shared memory area cannot be deleted. Need to use shmctl perhaps ipcrm Delete.
4.shmctl
 Function prototype: int shmctl(int shmid, int cmd, struct shmid_ds* buf);
Function function: interface with message queue msgctl The function is almost the same, shmctl Three commands are also provided.
IPC_RMID:Delete by shmid Uniquely identified shared memory area. At this time, the third parameter is not used and is passed in NULL. 
IPC_SET:set up shmid_ds The three members of the are: shm_perm.uid,shm_perm.gid and shm_perm.mode. 
IPC_STAT:buf As an outgoing parameter, get shmid Uniquely identified shared memory shmid_ds Structure.

4, Shared memory combat code

// Sender process
#include <stdio.h>
#include <assert.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#define PAGESIZE 4096

int main() {
	int shmid = shmget((key_t) 123, PAGESIZE, 0664|IPC_CREAT);
	assert(shmid != -1);
	
	char * p = (char*)shmat(shmid, NULL, 0);
	assert(p != (char*)-1);
	while (1) {
		printf("input: ");
		fgets(p, PAGESIZE-1, stdin);
		if (strncmp(p, "end", 3) == 0) break;
	}
	shmdt(p);
	return 0;
}


//Receiver process
#include <stdio.h>
#include <assert.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#define PAGESIZE 4096

int main() {
	int shmid = shmget((key_t) 123, PAGESIZE, 0664|IPC_CREAT);
	assert(shmid != -1);
	
	char * p = (char*)shmat(shmid, NULL, 0);
	assert(p != (char*)-1);
	while (1) {
		if (strncmp(p, "end", 3) == 0) break;
		printf("%s ", p);
		sleep(1);
	}
	shmdt(p);
	return 0;
}

5, Discussion on process security

In the above code, because different processes are not mutually exclusive to the shared memory critical area, when the CPU time slice allocated by the operating system to the process is used, the current process may not complete the task, and another process has taken the data of the unfinished task from the shared memory. This problem is very fatal in process communication, So how to solve the problem of data synchronization and mutual exclusion in the process of shared memory communication, so as to avoid data confusion? Please see the next blog, the use of semaphores.

Added by mounika on Thu, 24 Feb 2022 09:45:05 +0200