当前位置:网站首页>Shared memory communication between processes
Shared memory communication between processes
2022-06-21 14:50:00 【User 6978604】
Shared memory
Shared memory is mapping a piece of memory that can be accessed by other processes , This shared memory is created by a process , But multiple processes can access . Shared memory is the fastest IPC The way , It is specially designed for the low efficiency of other inter process communication modes .
But it does not provide a synchronization mechanism , That is, before a process finishes writing to shared memory , It does not prevent the second process from starting to read it , Therefore, we need to artificially prevent synchronization through other mechanisms .
shmget() function
Used to get a shared memory identifier or create a shared memory .
The function prototype :
int shmget(key_t key, size_t size, int shmflg);Parameters | explain |
|---|---|
key | Key value identifying shared memory ,shmget() When the function succeeds, it returns an and key Associated shared memory identifier ( Non-negative integer ), For subsequent shared memory functions . Call failure returns -1. |
size | Indicates the size of the shared memory , In bytes |
shmflg | Authority sign IPC_CREAT If shared memory does not exist , Create a shared memory , Otherwise, open the operation . IPC_EXCL Only when shared memory does not exist , New shared memory is created , Otherwise, there will be an error . |
shmat() function
After the shared memory is created for the first time , It can't be accessed by any process yet ,shmat() The function is used to start access to the shared memory , And connect the shared memory to the address space of the current process .
Prototype :
void *shmat(int shmid, const void *shmaddr, int shmflg)Parameters | explain |
|---|---|
shmid | Shared storage id, Such as shmget() The return value of the function |
shmaddr | Specifies the location of the shared memory connection to the current process , It's usually 0, Means to let the kernel decide an appropriate address location |
shmflg | SHM_RDONLY: Read only mode , Others are in read-write mode , Such as 0 |
When the call succeeds, it returns a pointer to the first byte of shared memory , If the call fails, it returns -1.
shmdt() function
And shmat The function is the opposite , Is the address used to disconnect from the shared memory attachment point , Prohibit this process from accessing this shared memory , But it is not to delete the shared memory .
Prototype :
int shmdt(const void *shmaddr);shmaddr: The starting address of the connected shared memory , Such as shmat() The return value of the function . Return when the call is successful 0, Return... On failure -1.
shmctl() function
Control shared memory .
Prototype :
int shmctl(int shm_id, int command, struct shmid_ds *buf);Parameters | explain |
|---|---|
shm_id | Shared memory identifier , Such as shmget() The return value of |
command | Some orders , Such as IPC_STAT: Get the state of shared memory , Put the shared memory shmid_ds The structure is copied to buf in IPC_SET: If the process has sufficient permissions , Set the current association value of shared memory to shmid_ds The value given in the structure IPC_RMID: Delete this shared memory |
buf | Shared memory management structure . |
shmid_ds structure Include at least the following members :
struct shmid_ds
{
uid_t shm_perm.uid;
uid_t shm_perm.gid;
mode_t shm_perm.mode;
};For example, a simple example , Parent and child processes communicate by sharing memory :
/*
* @Author: YaleXin
* @Date: 2020-04-22 14:22:16
* @LastEditTime: 2020-04-22 21:38:34
* @LastEditors: YaleXin
* @Description:
* @FilePath: \my_c_workspace\others\shareMemory.c
* @ Prayer does not appear BUG
*/
#include <stdio.h>
#include <string.h>
#include <sys/shm.h>
#include <unistd.h>
struct shareMemoryDate {
int mod;
char msg[100];
};
int main() {
int *shm = NULL;
struct shareMemoryDate *share;
// Create a shared memory
// IPC_CREAT Indicates if the shared memory does not exist , Create a shared memory , Otherwise, open the operation .
// Need and IPC Object access rights ( Such as 0600) Conduct | Operation to determine the access rights of the semaphore set
int shm_id =
shmget((key_t)0, sizeof(struct shareMemoryDate), 0600 | IPC_CREAT);
if (shm_id == -1) {
printf(" Failed to create shared memory , I don't know why \n");
return 0;
}
int pId = fork();
if (pId == -1) {
printf(" Failed to create child process , I don't know why \n");
} else if (pId == 0) {
// Subprocesses
// Connect shared memory to the address space of the current process
shm = shmat(shm_id, 0, 0);
if (shm == NULL) {
printf(" link failure , I don't know why \n");
return 0;
}
share = (struct shareMemoryDate *)shm;
char buffer[100];
printf(" I'm a subprocess , Please enter what you want to write to the shared memory :\n");
fgets(buffer, sizeof(buffer), stdin);
strcpy(share->msg, buffer);
// Indicates that the data has been written
share->mod = 1;
// Detach shared memory from the current process
if (shmdt(shm) == -1) {
printf(" Detach failed , I don't know why \n");
}
} else if (pId > 0) {
// The parent process
// Connect shared memory to the address space of the current process
shm = shmat(shm_id, 0, 0);
if (shm == NULL) {
printf(" link failure , I don't know why \n");
// Delete shared memory
if (shmctl(shm_id, IPC_RMID, 0) == -1) {
printf("( Can't link ) Failed to delete shared memory , I don't know why \n");
return 0;
}
}
share = (struct shareMemoryDate *)shm;
// Wait for the child process to finish writing
while (share->mod != 1) sleep(1);
printf(" I'm the parent process , Let me see what my child processes have written in shared memory :\n");
printf("%s\n", share->msg);
printf(" Oh , It's these ghosts \n");
// Delete shared memory
if (shmctl(shm_id, IPC_RMID, 0) == -1) {
printf("( Finished reading ) Failed to delete shared memory , I don't know why \n");
}
}
return 0;
}debugging :
[email protected]:/media/yalexin/ Software /my_c_workspace/others$ gcc -o share shareMemory.c
[email protected]:/media/yalexin/ Software /my_c_workspace/others$ ./share
I'm a subprocess , Please enter what you want to write to the shared memory :
How do you do
I'm the parent process , Let me see what my child processes have written in shared memory :
How do you do
Oh , It's these ghosts
[email protected]:/media/yalexin/ Software /my_c_workspace/others$ 边栏推荐
- Mysql5.7 setup password and remote connection
- Decipher Bishengyuan: is it tea that consumers buy, or is it IQ tax?
- T32 custom menu bar
- 模拟设计磁盘文件的链接存储结构
- Promotion guide for large enterprises: material preparation, PPT writing and on-site defense
- . bash_ profile
- Is it safe to open a securities account by downloading the app of qiniu school? Is there a risk?
- Subshell
- Indexes, constraints and views in Oracle Database
- JS hand tear pen test questions ~ not sorted out
猜你喜欢

Summary of web development technology knowledge

Qt-3-basic components

Teach you to stop visiting a website

Select everything between matching brackets in vs Code - select everything between matching brackets in vs Code

Application GDB debugging

PCA dimension reduction application of OpenCV (I)

Alibaba cloud energy consumption treasure will be released soon to help SMEs' green upgrading and participate in the carbon neutral trillion market

P24 de noise

Qt-3-basic assembly 2

Sliding validation tool class
随机推荐
2021-2022 recall of the final exam questions of non relational database of Shandong University
[untitled] fish pond forwarding command
Small case of throttling function
通过编译内核的方式增加系统调用
Write a compile time annotation
Continuous attack animation
Numpy: basic package for high performance scientific computing & data analysis
SSH based command operation
C language function fgets
Kubeneters installation encountered gcr The IO image warehouse cannot be pulled
Color segmentation based on RGB difference method
New project template of punctual atom F103 based on firmware library
Qt-6-file IO
2022 Hunan top eight (Safety Officer) simulated test question bank and answers
Niuke - real exercise-01
UBI error: ubi_ read_ volume_ table: the layout volume was not found
Three versions realize black-and-white theme switching
What fun things can a desk service do
What is the server room
养老年金险是理财产品吗?资金安全吗?