一個進程寫數據,一個進程讀數據
寫進程:
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; }