当前位置:网站首页>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
边栏推荐
- zhvoice
- Which websites can I search for references when writing a thesis?
- TypeError: Cannot read properties of undefined (reading ***)
- NC24840 [USACO 2009 Mar S]Look Up
- AcWing_ 188. Warrior cattle_ bfs
- 论文的英文文献在哪找(除了知网)?
- sysdig分析容器系统调用
- 接口自动化覆盖率统计——Jacoco使用
- 哪些软件可以整篇翻译英文论文?
- What are the projects of metauniverse and what are the companies of metauniverse
猜你喜欢

Pytorch里面多任务Loss是加起来还是分别backward?

Xcode real machine debugging
![[shutter] open the third-party shutter project](/img/1a/e35d0180612d7e79b55e7818193740.jpg)
[shutter] open the third-party shutter project

Chinatelecom has maintained a strong momentum in the mobile phone user market, but China Mobile has opened a new track

Architecture: database architecture design

接口差异测试——Diffy工具

Open Source | Wenxin Big Model Ernie Tiny Lightweight Technology, Accurate and Fast, full Open Effect

Interface difference test - diffy tool

Cmake basic use

130 pages of PPT from the brick boss introduces the new features of Apache spark 3.2 & 3.3 in depth
随机推荐
Chapter 3 of getting started with MySQL: database creation and operation
Pytorch 20 realizes corrosion expansion based on pytorch
What are the projects of metauniverse and what are the companies of metauniverse
sysdig分析容器系统调用
S12. Verify multi host SSH mutual access script based on key
多进程编程(一):基本概念
论文的设计方案咋写?
Go自定义排序
Which software can translate an English paper in its entirety?
Explain in detail the process of realizing Chinese text classification by CNN
SQL query statement parameters are written successfully
35 pages dangerous chemicals safety management platform solution 2022 Edition
Create an interactive experience of popular games, and learn about the real-time voice of paileyun unity
Should you study kubernetes?
Open source | Wenxin big model Ernie tiny lightweight technology, which is accurate and fast, and the effect is fully open
The privatization deployment of SaaS services is the most efficient | cloud efficiency engineer points north
Chinatelecom has maintained a strong momentum in the mobile phone user market, but China Mobile has opened a new track
秒杀系统设计
Understanding and application of least square method
[target detection] r-cnn, fast r-cnn, fast r-cnn learning