One: What is shared memory
? ? ? ? The shared memory is the IPC (inter-process communication interprocess communication ) mechanism, and the other two types are semaphores and Message Queuing, which creates a special address range for process creation, just like malloc assigns. The process can connect the same piece of shared memory to its own address space. thereby manipulating shared memory. So. 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:
intshmget (key_t?key,? int? size,? int? SHMFLG);
Number of parameters: the first key is provided by the program and is used to name the shared memory. Assuming that 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. Contains permission values and Ipc_creat or IPC_EXCL. For example: 0600| Ipc_creat represents a read-write and assumes that the memory does not exist, create one.
?
Return: The call succeeded, returning the memory ID. Failed, return-1.
Connection function:
void*shmat (intshmid,? Const? void*shmaddr,? int? SHMFLG);
Role://map process and address space for shared memory
Number of references:
? ? ? ? ? ? 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. is 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:
intshmdt (const? void*shmaddr);//for separating process space and shared memory segments
Return: Call succeeded, return 0?? Returns-1.
To delete a shared memory segment function:
intshmctl (intshmid,? int? cmd,? structshmid_ds?*buf);
Number of references:
? ? ? ? ? ? The first shmid is the creation of a function return identity.
? ? ? ? ? ? The second cmd is for a shared memory operation. Usually Ipc_rmid? represents the deletion.
? ? ? ? ? ? The third is usually null
Linux Learning log-shared memory