c++ 如何从共享内存中检索数据

hzbexzde  于 2022-12-24  发布在  其他
关注(0)|答案(2)|浏览(180)

我试图在共享内存中存储指向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
piok6c0g

piok6c0g1#

在这里的代码中

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
}

如果你试图存储一个指针,请记住你存储的指针在另一个进程中几乎肯定是无效的,并且不会像你期望的那样工作。

qhhrdooz

qhhrdooz2#

您正在损坏用于存储数据的for循环中pos的值。请使用*pos = *A;代替pos = A;
还要考虑一下,你是想保留新创建的A的内存位置,还是想把A的数据保存到共享内存中,我的修改会保存数据。

相关问题