命令
- ipcs 命令查看共享内存、消息队列、管道等相关信息
- ipcs -m 查看共享内存的信息
代码
- 创建共享内存
- 共享内存 关联 进程
- 分离共享内存
- 删除共享内存
#include <sys/shm.h>
#include <iostream>#define BUF_SIZE 1024int main() {int share_id = 0;//创建共享内存if ((share_id = shmget(IPC_PRIVATE,BUF_SIZE,0666))<0){//IPC_PRIVATE 系统分配管理,其key以0x00000000标识perror("shmget error!");exit(1);} else{printf("created shared-memory:%d\n",share_id);system("ipcs -m");}//共享内存 关联 逻辑指针void *share_add;if((share_add = shmat(share_id,0,0)) < (void *)0){perror("shmat error!");exit(1);}else{printf("attached shared-memory!\n");system("ipcs -m");}//分离共享内存if((shmdt(share_add))<0){perror("shmdt error!");exit(1);}else{printf("separate shared-memory!\n");system("ipcs -m");}//删除共享内存if ((shmctl(share_id,IPC_RMID,0))<0){perror("shmctl error!");exit(1);}else{printf("release shared-memory!\n");system("ipcs -m");}return 0;
}
代码
- 服务器产生数据,客户端输出数据,服务器和客户端使用相同的共享内存
服务器
#include <sys/shm.h>
#include <iostream>
#include <unistd.h>#define BUF_SIZE 1024struct sys_data{float data_rh;float data_t;
};
int main(int argc,char* argv[]) {int share_id = 0;struct sys_data *struct_data{};//创建共享内存share_id = shmget((key_t)45958023,sizeof (sys_data),0666|IPC_CREAT);if (share_id == -1){perror("shmget error!");exit(-1);}else{printf("created shared-memory:%d\n",share_id);}//共享内存 关联 逻辑指针void *share_add;share_add = shmat(share_id,0,0);if (share_id == -1){perror("shmat error!");exit(-1);}float f_temp{};float f_humi{};struct_data = reinterpret_cast<struct sys_data *>(share_add);while (1){f_temp = rand() % 100;f_humi = rand() % 100;struct_data->data_rh = f_humi;struct_data->data_t = f_temp;sleep(1);}
// //分离共享内存
// if((shmdt(share_add))<0){
// perror("shmdt error!");
// exit(1);
// }
// //删除共享内存
// if ((shmctl(share_id,IPC_RMID,0))<0){
// perror("shmctl error!");
// exit(1);
// }else{
// printf("release shared-memory!\n");
// system("ipcs -m");
// }return 0;
}
客户端
#include <sys/shm.h>
#include <iostream>
#include <unistd.h>#define BUF_SIZE 1024struct sys_data{float data_rh;float data_t;
};
int main(int argc,char* argv[]) {int share_id = 0;struct sys_data *struct_data{};//创建共享内存share_id = shmget((key_t)45958023,sizeof (sys_data),0666|IPC_CREAT);if (share_id == -1){perror("shmget error!");exit(-1);}else{printf("created shared-memory:%d\n",share_id);}//共享内存 关联 逻辑指针void *share_add;share_add = shmat(share_id,0,0);if (share_id == -1){perror("shmat error!");exit(-1);}float f_temp{};float f_humi{};struct_data = reinterpret_cast<struct sys_data *>(share_add);while (1){sleep(2);printf("temp = %.lf,humi = %.lf\n",struct_data->data_t,struct_data->data_rh);}
// //分离共享内存
// if((shmdt(share_add))<0){
// perror("shmdt error!");
// exit(1);
// }
// //删除共享内存
// if ((shmctl(share_id,IPC_RMID,0))<0){
// perror("shmctl error!");
// exit(1);
// }else{
// printf("release shared-memory!\n");
// system("ipcs -m");
// }return 0;
}
参考链接
- 共享内存函数(shmget、shmat、shmdt、shmctl)及其范例