One: What is shared memory
shared memory belongs to the IPC (inter-process communication interprocess communication ) mechanism, and the other two are semaphores and Message Queuing, which creates a special address range for process creation, just like malloc assigns. A process can manipulate shared memory by connecting the same piece of shared memory to its own address space, so that shared memory provides a way to share and pass data between multiple processes. It is important to note that this mechanism does not provide a synchronization mechanism, so we need to take an effective mechanism to synchronize access to shared memory.
Two: Schematic diagram of shared memory
Three: Related functions
Header file:
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
To create or open a function:
int shmget (key_t key, int size, int shmflg);
Parameters: The first key is provided by the program and is used to name the shared memory. If the named shared memory is already open, the memory ID is returned directly.
The second Sie is the size of the specified memory.
The third is a masked composite value. Includes permission values and Ipc_creat or IPC_EXCL. Example: 0600| The ipc_creat represents a read-write and if the memory does not exist, create one.
Return: The call succeeded, returning the memory ID. Failed, return-1.
Connection function:
void *shmat (int shmid, const void *shmaddr, int shmflg);
Role://map process and address space for shared memory
Parameters:
The first shmid is the creation of a function return identity.
The second shmaddr is the address location where the process exists within the share. Usually null, let the system default.
The third SHMFLG is a bit ID. is typically 0
Return: The call succeeded, returning a pointer to the first byte of shared memory. Failed, returned-1;
Detach function:
int shmdt (const void *shmaddr);//for separating process space and shared memory segments
Return: Call succeeded, return 0 failed, return-1;
To delete a shared memory segment function:
int shmctl (int shmid, int cmd, struct shmid_ds *buf);
Parameters:
The first shmid is the creation of a function return identity.
The second cmd is for a shared memory operation. Typically deleted for Ipc_rmid delegates.
The third is usually null
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Linux Learning log-shared memory