Reputation: 1843
I have a struct definition as follows
struct s
{
int a;
};
struct s s1;
struct s s2;
I need to push both structure instances to shared memory.
char *data=(char *)shmat(m_sharedMemoryId,NULL,0);
memcpy(data,&s1,sizeof struct s);
I did for the 1st instance of structure.
How to do for the second instance? Is this possible in shared memory?
Plaftform : UNIX
Upvotes: 0
Views: 1178
Reputation: 148965
The shmat
calls only gets a pointer to a shared memory segment that should have previously be created with shmget
. You have 2 ways to deal with that :
allocate a segment that will hold an array for all your structs and then copy your structs to this array :
m_sharedMemoryId = shmget(key, sizeof(struct s) * nb, perm_flag);
struct s* data = shmat(m_sharedMemoryId,NULL,0);
and then you copy a struct s where you want in the array, here in position i :
memcpy(data + i,&s1,sizeof(struct s));
this is mainly to use if you have many little structures
allocate a different segment per each struct
m_sharedMemoryId = shmget(key, sizeof(struct s), perm_flag);
struct s* data = shmat(m_sharedMemoryId,NULL,0);
memcpy(data,&s1,sizeof(struct s));
and you repeat the allocation for each struct. This is to use if you have few big structs that you want to be able to deallocate separately
Upvotes: 2