c 共享内存demo
一个进程写数据,一个进程读数据
写进程:
1. shmget()获取共享内存
2. shmat()共享内存映射到进程空间
3. 写数据
读进程:
1. shmget()获取共享内存
2. shmat()共享内存映射到进程空间
3. 读数据
4. shmdt()共享内存从进程空间解除映射
5. shmctl()删除共享内存
读进程
// // Created by gxf on 2020/2/10. // #ifndef UNTITLED_MAIN_H #define UNTITLED_MAIN_H char *ftokFilePath = "/Users/gxf/CLionProjects/untitled/main.c"; int project_id = 10; typedef struct { int age; char name[50]; }person; #endif //UNTITLED_MAIN_H
#include <stdio.h> #include <sys/ipc.h> #include <sys/shm.h> #include <string.h> #include "main.h" int main() { key_t ftokRes = ftok(ftokFilePath, project_id); person *zhangsan; person lisi = {10, "lisi"}; int shmid = shmget(ftokRes, sizeof(person), IPC_CREAT | 0777); printf("shamid :%d\n", shmid); zhangsan = (person *)shmat(shmid, NULL, SHM_W); zhangsan->age = 20; strcpy(zhangsan->name, "zhangsan1111"); return 0; }
// // Created by gxf on 2020/2/10. // #include <stdlib.h> #include <stdio.h> #include <sys/ipc.h> #include <sys/shm.h> #include <string.h> #include "main.h" int main() { key_t ftokRes = ftok(ftokFilePath, project_id); printf("%d\n", ftokRes); person *zhangsan = malloc(sizeof(person)); int shmid = shmget(ftokRes, sizeof(person), IPC_CREAT); person *shmaddr = shmat(shmid, NULL, SHM_R); memcpy(zhangsan, shmaddr, sizeof(person)); printf("age:%d, name:%s\n", zhangsan->age, zhangsan->name); int res = shmdt(shmaddr); if (res) fprintf(stderr, "shmdt fail"); res = shmctl(shmid, IPC_RMID, NULL); if (res) fprintf(stderr, "rm ipcs -m fail"); return 0; }
Please call me JiangYouDang!