有人可以就我可能会出错的地方给出一些指示。我试图将指向结构类型元素的指针存储在共享内存中。但是在获取相同的内容时,我得到的只是零。
代码:
#include<iostream>
#include<cstdio>
#include<sys/shm.h>
#include<sys/stat.h>
using namespace std;
typedef struct demo
{
int sensorID;
float value;
int time;
}demo;
int main()
{
key_t key;
int shmid;
demo *ptr;
key = ftok("/home/dilbert/work",'R');
shmid = shmget(key,4096*2, 0755 | IPC_CREAT);
ptr = (demo*)shmat(shmid, (void*)0, 0); //Is this step right?
//I casted the void ptr into demo ptr type
if(ptr == (demo*)(-1))
perror("shmat");
demo *pos = ptr;
for(int i=0; i<10; ++i)
{
demo *A=new demo; //Creating a struct elem
A->sensorID=i+10; //Storing some data
A->value=2*i+98.344;
A->time=3*i*1000;
pos = A; //Keeping the pointer to it in shared memory
++pos; //Incrementing the pointer
}
pos = ptr; //Reset the pointer back to start of shared memory. Might be going wrong here.
for(int i=0; i<10; ++i) //Now start printing the data.
{
cout<<"Sensor: "<<pos->sensorID<<" Value: "<<pos->value<<" Time: "<<pos->value<<"\n";
++pos;
}
//Just a demo program. So did not bother to delete the pointers in shared memory. I think I should because shared memory destruction will not call delete for its elements.
shmdt(ptr);
shmctl(shmid, IPC_RMID, NULL);
return 0;
}
我得到的结果是:
Sensor: 0 Value: 0 Time: 0
Sensor: 0 Value: 0 Time: 0
Sensor: 0 Value: 0 Time: 0
Sensor: 0 Value: 0 Time: 0
Sensor: 0 Value: 0 Time: 0
Sensor: 0 Value: 0 Time: 0
Sensor: 0 Value: 0 Time: 0
Sensor: 0 Value: 0 Time: 0
Sensor: 0 Value: 0 Time: 0
Sensor: 0 Value: 0 Time: 0