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
4

2 回答 2

1

您正在破坏用于存储数据pos的 for 循环中的值。使用而不是*pos = *A;pos = A;

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

于 2013-05-09T07:39:56.250 回答
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
}

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

于 2013-05-09T07:40:44.523 回答