gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 09:45:49 25 4
gpt4 key购买 nike

我试图在共享内存中存储指向结构类型元素的指针。但是在获取相同的东西时,我得到的只是零。

代码:

#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

最佳答案

这里的代码

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
}

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

关于c++ - 如何从共享内存中检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16456521/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com