查看共享内存使用情况
ipcs -m
删除指定key的共享内存
ipcrm -m shmid
例一:
server.c (创建共享内存并写入数据)
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/ipc.h> #include <sys/shm.h>// 定义学生结构体 typedef struct {int id;char name[32];float score; } Student;// 定义班级结构体(包含多个学生) typedef struct {int count;Student students[10]; // 假设班级最多10人 } Classroom;int main() {// 1. 创建共享内存int shmid = shmget((key_t)12345, 1024, 0666 | IPC_CREAT);if (shmid == -1){perror("shmget failed");exit(EXIT_FAILURE);}// 2. 映射共享内存Classroom *shared_class = (Classroom *)shmat(shmid, NULL, 0);if (shared_class == (void *)-1){perror("shmat failed");exit(EXIT_FAILURE);}// 3. 写入班级数据shared_class->count = 3; // 班级有3名学生// 学生1shared_class->students[0].id = 1001;strcpy(shared_class->students[0].name, "张三");shared_class->students[0].score = 89.5f;// 学生2shared_class->students[1].id = 1002;strcpy(shared_class->students[1].name, "李四");shared_class->students[1].score = 92.0f;// 学生3shared_class->students[2].id = 1003;strcpy(shared_class->students[2].name, "王五");shared_class->students[2].score = 78.5f;printf("数据已写入共享内存,按任意键释放资源...\n");getchar();// 4. 断开映射if (shmdt(shared_class) == -1){perror("shmdt failed");}// 5. 删除共享内存if (shmctl(shmid, IPC_RMID, 0) == -1){perror("shmctl failed");}return 0; }
client.c (读取共享内存数据)
#include <stdio.h> #include <stdlib.h> #include <sys/ipc.h> #include <sys/shm.h>// 必须与server.c中的定义一致 typedef struct {int id;char name[32];float score; } Student;typedef struct {int count;Student students[10]; } Classroom;int main() {// 1. 获取共享内存int shmid = shmget((key_t)12345, 0, 0666);if(shmid == -1) {perror("shmget failed");exit(EXIT_FAILURE);}// 2. 映射共享内存Classroom *shared_class = (Classroom *)shmat(shmid, NULL, 0);if(shared_class == (void *)-1) {perror("shmat failed");exit(EXIT_FAILURE);}// 3. 读取并显示数据 printf("班级人数: %d\n", shared_class->count);for(int i = 0; i < shared_class->count; i++) {printf("学生%d: ID=%d, 姓名=%s, 分数=%.1f\n",i+1,shared_class->students[i].id,shared_class->students[i].name,shared_class->students[i].score);}// 4. 断开映射if(shmdt(shared_class) == -1) {perror("shmdt failed");}return 0; }
输出结果: