当前位置:网站首页>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
边栏推荐
- Matlab 信号处理【问答笔记-1】
- Hit the industry directly! The propeller launched the industry's first model selection tool
- Basic 10 of C language: array and pointer
- Bypass AV with golang
- sysdig分析容器系统调用
- Slf4j + logback logging framework
- MFC gets the current time
- Nc50528 sliding window
- NC24325 [USACO 2012 Mar S]Flowerpot
- How to write the design scheme of the thesis?
猜你喜欢

sysdig分析容器系统调用

Cmake basic use

What are the projects of metauniverse and what are the companies of metauniverse

CADD course learning (4) -- obtaining proteins without crystal structure (Swiss model)

130 pages of PPT from the brick boss introduces the new features of Apache spark 3.2 & 3.3 in depth
![[shutter] shutter photo wall (center component | wrap component | clickrrect component | stack component | positioned component | button combination component)](/img/c5/2f65d37682607aab98443d7f1ba775.jpg)
[shutter] shutter photo wall (center component | wrap component | clickrrect component | stack component | positioned component | button combination component)

The privatization deployment of SaaS services is the most efficient | cloud efficiency engineer points north

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

请问大家在什么网站上能查到英文文献?

Improvement of RTP receiving and sending PS stream tool (II)
随机推荐
写论文可以去哪些网站搜索参考文献?
大学生课堂作业2000~3000字的小论文,标准格式是什么?
What website can you find English literature on?
Interface difference test - diffy tool
Open source | Wenxin big model Ernie tiny lightweight technology, which is accurate and fast, and the effect is fully open
洛谷_P1149 [NOIP2008 提高组] 火柴棒等式_枚举打表
布隆过滤器
[shutter] shutter photo wall (center component | wrap component | clickrrect component | stack component | positioned component | button combination component)
监控容器运行时工具Falco
CADD course learning (4) -- obtaining proteins without crystal structure (Swiss model)
Monitor container runtime tool Falco
多进程编程(三):消息队列
The privatization deployment of SaaS services is the most efficient | cloud efficiency engineer points north
Bigder: how to deal with the bugs found in the 32/100 test if they are not bugs
MATLAB signal processing [Q & a notes-1]
多进程编程(五):信号量
v8
Realization of mask recognition based on OpenCV
Slf4j + Logback日志框架
[target detection] r-cnn, fast r-cnn, fast r-cnn learning