共享内存的创建与读取、打印
#include<stdio.h>
#include<string.h>
#include<fcntl.h>
#include<stdlib.h>
#include<sys/ipc.h>
#include<sys/shm.h>
struct sys_data{
float data_rh;
float data_t;
};
int main(){
void* shm=(void*)0;
int shmid;
struct sys_data *da=0;
float ftemp=0.0,fhumi=0.0;
shmid=shmget((key_t)8891,sizeof(struct sys_data),0666|IPC_CREAT); //创建共享内存
if(shmid == -1){
printf("shmget error\n");
exit(-1);
}else{ printf("shmid = %d\n",shmid);}
shm = shmat(shmid,(void*)0,0); //将共享内存映射到调用进程的地址空间
if(shm == (void*)(-1)){
printf("shmat error\n");
exit(-1);
}
da = shm; //将结构da指针指向shm=shmat()返回的地址的首地址的值,将结构体的内容存放在共享内存中。
while(1){
sleep(1);
printf("temp=%.1f,humi=%.1f\n",da->data_t,da->data_rh);
}
return 0;
}
~
往共享内存中存放数据
#include<stdio.h>
#include<string.h>
#include<fcntl.h>
#include<stdlib.h>
#include<sys/ipc.h>
#include<sys/shm.h>
struct sys_data{
float data_rh;
float data_t;
};
int main(){
void* shm=(void*)0;
int shmid;
struct sys_data *da=0;
float ftemp=0.0,fhumi=0.0;
shmid=shmget((key_t)8891,sizeof(struct sys_data),0666|IPC_CREAT);
if(shmid == -1){
printf("shmget error\n");
exit(-1);
}else{ printf("shmid = %d\n",shmid);}
shm = shmat(shmid,(void*)0,0);
if(shm == (void*)(-1)){
printf("shmat error\n");
exit(-1);
}
da = shm;
while(1){
ftemp = rand()%100;
fhumi= rand()%100;
da->data_t=ftemp;
da->data_rh=fhumi;
sleep(1);
}
}
~
在上面这两个程序中,实现共享内存的使用采用:1、创建共享内存 2、将共享内存映射到当前进程的地址空间 3、定义相同的结构体,同时将结构体指向shmat()函数返回的地址