当前位置:网站首页>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
边栏推荐
- Where can I find foreign papers?
- 论文的英文文献在哪找(除了知网)?
- Array de duplication
- Slf4j + logback logging framework
- 67 page overall planning and construction plan for a new smart city (download attached)
- [shutter] Introduction to the official example of shutter Gallery (project introduction | engineering construction)
- Bigder:32/100 测试发现的bug开发认为不是bug怎么处理
- Hit the industry directly! The propeller launched the industry's first model selection tool
- Is there a specific format for English papers?
- Pytorch 20 realizes corrosion expansion based on pytorch
猜你喜欢

Angled detection frame | calibrated depth feature for target detection (with implementation source code)

Digital collection trading website domestic digital collection trading platform

Hit the industry directly! The propeller launched the industry's first model selection tool

多进程编程(二):管道

35 pages dangerous chemicals safety management platform solution 2022 Edition

Is the multitasking loss in pytoch added up or backward separately?
![Luogu_ P2010 [noip2016 popularization group] reply date_ Half enumeration](/img/a3/55bb71d39801ceeee421a0c8ded333.png)
Luogu_ P2010 [noip2016 popularization group] reply date_ Half enumeration
![[target detection] r-cnn, fast r-cnn, fast r-cnn learning](/img/f0/df285f01ffadff62eb3dcb92f2e04f.jpg)
[target detection] r-cnn, fast r-cnn, fast r-cnn learning

Which software can translate an English paper in its entirety?

Architecture: database architecture design
随机推荐
Top Devops tool chain inventory
sysdig分析容器系统调用
Pat 1030 travel plan (30 points) (unfinished)
Interface automation coverage statistics - used by Jacobo
Returns the root node of the largest binary search subtree in a binary tree
Happy Lantern Festival, how many of these technical lantern riddles can you guess correctly?
RTP 接发ps流工具改进(二)
Don't want teachers to see themselves with cameras in online classes? Virtual camera you deserve!
Cmake basic use
CMake基本使用
开源了 | 文心大模型ERNIE-Tiny轻量化技术,又准又快,效果全开
pageoffice-之bug修改之旅
洛谷_P1149 [NOIP2008 提高组] 火柴棒等式_枚举打表
Basic 10 of C language: array and pointer
Go自定义排序
Digital twin visualization solution digital twin visualization 3D platform
Analyze ad654: Marketing Analytics
Is the multitasking loss in pytoch added up or backward separately?
Understanding and application of least square method
What are the projects of metauniverse and what are the companies of metauniverse