有人可以提供一些關於我可能出錯的地方。我試圖在共享內存中存儲結構類型元素的指針。但取得同樣的結果,我得到的是零。無法從共享內存中檢索數據
代碼:
#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
它工作。非常感謝。 我正在考慮存儲指向結構元素的指針,因爲元素可能很大。所以想着節省空間並讓共享內存存儲更多元素。 – NotAgain 2013-05-09 08:43:40