2013-05-09 49 views
0

有人可以提供一些關於我可能出錯的地方。我試圖在共享內存中存儲結構類型元素的指針。但取得同樣的結果,我得到的是零。無法從共享內存中檢索數據

代碼:

#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 

回答

1

你破壞的pos值在for循環存儲數據。使用pos = A;*pos = *A;代替

而且也想想你想保留新創建的存儲器的存儲位置爲A,或者您希望將數據從A保存到共享內存。我的更改將存儲數據。

+0

它工作。非常感謝。 我正在考慮存儲指向結構元素的指針,因爲元素可能很大。所以想着節省空間並讓共享內存存儲更多元素。 – NotAgain 2013-05-09 08:43:40

1

在這裏的代碼

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 
} 

你正在創建非共享內存中的對象。此外,你並沒有將指針存儲到共享內存中,而是實際上修改了指針(實際上指向本地內存)。

你試圖存儲實際的對象還是隻是一個指針到共享內存?如果你的意思是存儲實際的對象,你要使用類似

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;   //Store object in shared memory 
     ++pos;    //Incrementing the pointer 
} 

如果你想存儲的指針,記住,你店將幾乎可以肯定的指針是另一個進程中無效並不會像你期望的那樣工作。

+0

謝謝。有效。 非常感謝。我正在考慮存儲指針,以使共享內存存儲更多的數據。由於結構的元素可以是大尺寸的。指針的大小是固定的。但其他進程可能無法提取數據的事實令人擔憂。將不得不檢查更多。 – NotAgain 2013-05-09 08:42:06