当前位置:网站首页>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
边栏推荐
- redis21道经典面试题,极限拉扯面试官
- 开源了 | 文心大模型ERNIE-Tiny轻量化技术,又准又快,效果全开
- Andorid 获取系统标题栏高度
- Interface difference test - diffy tool
- Chapter 3 of getting started with MySQL: database creation and operation
- Returns the root node of the largest binary search subtree in a binary tree
- 多进程编程(五):信号量
- Maya fishing house modeling
- [shutter] shutter photo wall (center component | wrap component | clickrrect component | stack component | positioned component | button combination component)
- Slf4j + logback logging framework
猜你喜欢
带角度的检测框 | 校准的深度特征用于目标检测(附实现源码)
Basic 10 of C language: array and pointer
Interpretation of new plug-ins | how to enhance authentication capability with forward auth
DotNet圈里一个优秀的ORM——FreeSql
Matlab 信号处理【问答笔记-1】
QT 如何将数据导出成PDF文件(QPdfWriter 使用指南)
论文的英文文献在哪找(除了知网)?
来自数砖大佬的 130页 PPT 深入介绍 Apache Spark 3.2 & 3.3 新功能
洛谷_P2010 [NOIP2016 普及组] 回文日期_折半枚举
Xcode real machine debugging
随机推荐
v8
Returns the root node of the largest binary search subtree in a binary tree
pageoffice-之bug修改之旅
多进程编程(一):基本概念
多进程编程(三):消息队列
Chapter 4 of getting started with MySQL: data types stored in data tables
写论文可以去哪些网站搜索参考文献?
大学生课堂作业2000~3000字的小论文,标准格式是什么?
Analyze ad654: Marketing Analytics
yolov5detect. Py comment
Markdown使用教程
maya渔屋建模
Understanding and application of least square method
Missing number
Practical series - free commercial video material library
AcWing_188. 武士风度的牛_bfs
The privatization deployment of SaaS services is the most efficient | cloud efficiency engineer points north
毕业总结
Implement the foreach method of array
Which software can translate an English paper in its entirety?