无法从共享内存中检索数据

时间:2013-05-09 07:20:56

标签: c++ linux shared-memory

有人可以就我可能出错的地方给出一些指示。我试图在共享内存中存储指向struct类型元素的指针。但是在取得同样的东西时,我得到的是零。

代码:

#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

2 个答案:

答案 0 :(得分:1)

您在存储数据的for循环中损坏了pos的值。使用*pos = *A;代替pos = A;

还要考虑一下,您是要保留A新创建的内存的内存位置,还是要将A中的数据存储到共享内存中。我的更改将存储数据。

答案 1 :(得分: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
}

如果您正在尝试存储指针,请记住,您存储的指针几乎肯定会在另一个进程中无效,并且无法按预期工作。