创建共享内存,往共享内存里写入数据
#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);
}
}
~
将写入共享内存的内容打印出来
#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){
sleep(1);
printf("temp=%.1f,humi=%.1f\n",da->data_t,da->data_rh);
}
return 0;
}
~