How to access variables in shared memory
Posted
by
user1723361
on Stack Overflow
See other posts from Stack Overflow
or by user1723361
Published on 2012-10-05T15:14:28Z
Indexed on
2012/10/05
15:37 UTC
Read the original article
Hit count: 198
I am trying to create a shared memory segment containing three integers and an array. The segment is created and a pointer is attached, but when I try to access the values of the variables (whether changing, printing, etc.) I get a segmentation fault.
Here is the code I tried:
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#define SIZE 10
int* shm_front;
int* shm_end;
int* shm_count;
int* shm_array;
int shm_size = 3*sizeof(int) + sizeof(shm_array[SIZE]);
int main(int argc, char* argsv[])
{
int shmid;
//create shared memory segment
if((shmid = shmget(IPC_PRIVATE, shm_size, 0644)) == -1)
{
printf("error in shmget");
exit(1);
}
//obtain the pointer to the segment
if((shm_front = (int*)shmat(shmid, (void *)0, 0)) == (void *)-1)
{
printf("error in shmat");
exit(1);
}
//move down the segment to set the other pointers
shm_end = shm_front + 1;
shm_count = shm_front + 2;
shm_array = shm_front + 3;
//tests on shm
//*shm_end = 10; //gives segmentation fault
//printf("\n%d", *shm_front); //gives segmentation fault
//clean-up
//get rid of shared memory
shmdt(shm_front);
shmctl(shmid, IPC_RMID, NULL);
//printf("\n\n");
return 0;
}
I tried accessing the shared memory by dereferencing the pointer to the struct, but got a segmentation fault each time.
© Stack Overflow or respective owner