我试图在共享内存中存储指向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条答案
按热度按时间piok6c0g1#
在这里的代码中
你在非共享内存中创建了一个对象,而且,你并没有把一个指针存储到共享内存中,你实际上是在修改指针本身(实际上是指向本地内存)。
你是想存储实际的对象,还是仅仅是一个指向共享内存的指针?如果你想存储实际的对象,你需要使用类似
如果你试图存储一个指针,请记住你存储的指针在另一个进程中几乎肯定是无效的,并且不会像你期望的那样工作。
qhhrdooz2#
您正在损坏用于存储数据的for循环中
pos
的值。请使用*pos = *A;
代替pos = A;
还要考虑一下,你是想保留新创建的
A
的内存位置,还是想把A
的数据保存到共享内存中,我的修改会保存数据。