Reputation: 463
Two processes (or programs) are using the same System V shared memory segment, which is basically this struct
/* file: shmem.h */
struct Shmem{
int *array;
}
From program1 I initialize the shared memory like this
/* file: program1.c */
Shmem_init(shmem, siz);
for (int i=0; i<siz; i++)
shmem->array[i] = number;
where Shmem_init
is implemented like this
/* file: shmem.c */
void Shmem_init(Shmem *shmem, int siz){
shmem->array = (int *)malloc(siz * sizeof(int));
}
Then if I try to access shmem->array[i]
from program2, my program just freezes and does nothing(undefined behavior?)
Should I have expected that? Is it because the elements array[1], array[2], ...
are stored in program1's heap and therefore are not accesible by program2?
Thanks
[ Don't mind about stuff like shmget()
and shmat()
, those are taken care of ]
Upvotes: 0
Views: 1246
Reputation: 1569
Since you don't give details on your code, i'm assuming you are using boost shared memory. And you are using the example in the docs.
//////////////////
/// first process
#define COUNT 1000
//Set size
shm.truncate(COUNT*sizeof(int) + sizeof(int)); //COUNT*sizeof(data type) + sizeof(shmem_size)
mapped_region region(shm, read_write);
int *size = static_cast<int*> (region.get_address());
*size = COUNT;
Shmem *mem = reinterpret_cast<Shmem*>(size+1);
... // fill mem->array
//////////////////
/// second process
//Map the whole shared memory in this process
mapped_region region(shm, read_only);
int size = *static_cast<int*> (region.get_address());
Shmem *mem = reinterpret_cast<Shmem*>(static_cast<int*>(region.get_address())+1);
Upvotes: 0
Reputation: 9288
You answered your own question... The pointer returned by malloc is only valid for the process that called it.
Upvotes: 1