当前位置:网站首页>Multiprocess programming (4): shared memory
Multiprocess programming (4): shared memory
2022-07-03 00:23:00 【HDD615】
Definition :
Shared memory (Shared Memory) It allows two or more processes to access the same memory space , Is the most efficient way to communicate in multiple processes .
The operating system arranges the shared memory between different processes into the same physical memory , Processes can connect shared memory to their own address space , If a process modifies data in shared memory , The data read by other processes will also change . Because shared memory will become part of the process user space , All this communication does not require kernel intervention .
Shared memory does not provide a locking mechanism , in other words , When a process reads and writes shared memory , It will not prevent other processes from reading and writing to it , There may be data disorder .
function :
1、 Required header file
#include <sys/ipc.h>
#include <sys/shm.h>
2、shmget() Get or create shared memory
// Get or create shared memory
int shmget(key_t key, size_t size, int shmflg);
- key The memory key value is shared , It's an integer , Is the number of shared memory in the system , Different shared memory has different numbers . Generally, hexadecimal is used .
- size Indicates the size of the shared memory to be created , In bytes
- shmflg Indicates access to shared memory , The same permissions as files ,
0666 | IPC_CREAT Indicates that all users can read and write it
- Return value : Returns the shared memory ID
3、shmat() Connect the shared memory to the address space of the current process
void *shmat(int shm_id, const void *shm_addr, int shmflg);
- shm_id By shmget Function return Identification number of shared memory
- shm_addr Specifies the location of the shared memory connection to the current process , Usually it is NULL, Let the system choose the address of shared memory .
- shm_flg Is a set of flag bits , Usually it is 0
- Return value :
Successful call : Returns a pointer to the first byte of shared memory
Call failed : return -1
4、shmdt() Separate shared memory from the current process , amount to shmat() The reverse operation of a function
int shmdt(const void *shmaddr);
- shmaddr yes shmat function Return address
- Return value :
Successful call : return 0
Call failed : return -1
5、shmctl() Delete shared memory
int shmctl(int shm_id, int command, struct shmid_ds *buf);
- shm_id Is the identification number of shared memory
- command Fill in IPC_RMID
- buf Fill in 0
- Return value :
Successful call : return 0
Call failed : return -1
Use steps
- call
shmget()Function to create a new shared memory segment or get the identification number of an existing shared memory segment . Return the required shared memory identifier that can be called later . - Use in process
shmat()Function with shared memory segment , That is, make the shared memory segment a part of the virtual memory of the calling process ( Process binding shared memory segment ) - Use
shmat()Returned memory address pointer , You can operate on the shared memory segment in the program ( Write operations / Read operations ). - call
shmdt()function , Separate the process from the shared memory segment , The process can no longer operate on shared memory .( Just separation , Shared memory still exists ) - call
shmctl()function , Delete shared memory segment , Only when the processes bound to the shared memory segment are separated , Will destroy , Only one process needs to perform this step .
give an example
// write_shm.c
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
int main()
{
int shmid; // Shared memory identifier
// Create shared memory , The key value is 0x5005, common 1024 byte .
if ( (shmid = shmget((key_t)0x5005, 1024, 0666 | IPC_CREAT)) == -1)
{
printf("shmat(0x5005) failed\n");
return -1;
}
char *ptext = NULL; // Pointer to shared memory
// Connect shared memory to the address space of the current process , from ptext The pointer points to it
ptext = (char *)shmat(shmid, NULL, 0);
// To operate this procedure ptext The pointer , Is to operate shared memory
char *str = "Hello world!";
memcpy(ptext, str, strlen(str));
// Detach shared memory from the current process
shmdt(ptext);
return 0;
}
// read_shm.c
int main()
{
int shmid; // Shared memory identifier
// Create shared memory , The key value is 0x5005, common 1024 byte .
if ( (shmid = shmget((key_t)0x5005, 1024, 0666 | IPC_CREAT)) == -1)
{
printf("shmat(0x5005) failed\n");
return -1;
}
char *ptext = NULL; // Pointer to shared memory
// Connect shared memory to the address space of the current process , from ptext The pointer points to it
ptext = (char *)shmat(shmid, NULL, 0);
// To operate this procedure ptext The pointer , Is to operate shared memory
printf("%s\n", ptext);
// Detach shared memory from the current process
shmdt(ptext);
// Delete shared memory
if (shmctl(shmid, IPC_RMID, 0) == -1)
{
printf("shmctl(0x5005) failed\n");
return -1;
}
}
read_shm.c Output result of :
Hello world!
It can be seen that ,write_shm.c Request shared memory , And write data ,read_shm Get the shared memory identification number , And bind the process , Read the data in the shared memory .
View shared memory
ipcs -m # View all existing shared memory segments
ipcrm -m shmid # According to the identification number of the shared memory segment , Delete shared memory
边栏推荐
- 開源了 | 文心大模型ERNIE-Tiny輕量化技術,又准又快,效果全開
- MySQL advanced learning notes (4)
- 在线预览Word文档
- [shutter] open the third-party shutter project
- yolov5detect. Py comment
- MATLAB signal processing [Q & a notes-1]
- Angled detection frame | calibrated depth feature for target detection (with implementation source code)
- SQL query statement parameters are written successfully
- Develop knowledge points
- Pat 1030 travel plan (30 points) (unfinished)
猜你喜欢

Shell脚本基本使用

Happy Lantern Festival, how many of these technical lantern riddles can you guess correctly?
![[shutter] open the third-party shutter project](/img/1a/e35d0180612d7e79b55e7818193740.jpg)
[shutter] open the third-party shutter project

Matlab 信号处理【问答笔记-1】

带角度的检测框 | 校准的深度特征用于目标检测(附实现源码)

RTP 接发ps流工具改进(二)

130 pages of PPT from the brick boss introduces the new features of Apache spark 3.2 & 3.3 in depth

pageoffice-之bug修改之旅

Additional: token; (don't read until you finish writing...)

QT 如何将数据导出成PDF文件(QPdfWriter 使用指南)
随机推荐
The privatization deployment of SaaS services is the most efficient | cloud efficiency engineer points north
開源了 | 文心大模型ERNIE-Tiny輕量化技術,又准又快,效果全開
[shutter] Introduction to the official example of shutter Gallery (project introduction | engineering construction)
写论文可以去哪些网站搜索参考文献?
How to write the design scheme of the thesis?
Bloom filter
Architecture: load balancing
AcWing_188. 武士风度的牛_bfs
S12. Verify multi host SSH mutual access script based on key
Which software can translate an English paper in its entirety?
Basic 10 of C language: array and pointer
Understanding and application of least square method
多进程编程(五):信号量
v8
In February 2022, the ranking list of domestic databases: oceanbase regained its popularity with "three consecutive increases", and gaussdb is expected to achieve the largest increase this month
35 pages dangerous chemicals safety management platform solution 2022 Edition
CADD course learning (4) -- obtaining proteins without crystal structure (Swiss model)
Using tensorflow to realize voiceprint recognition
多进程编程(二):管道
JSON转换工具类