how to create shared memory

Hi every one,
I need to create 8k bytes of shared memory area so what I have done is I am created a shared memory area as follows

Unsigned int *addr;
fd = shm_open( “/root/shmem1”, O_RDWR | O_CREAT, 0777 );
if( fd == -1 )
{
fprintf( stderr, “Open failed:%s\n”, strerror( errno ) );
return EXIT_FAILURE;
}

/* Set the memory object’s sizeas 8k*/
x= ftruncate( fd, 8192);
/here x value what I am getting is 0/
if( x == -1 )
{
fprintf( stderr, “ftruncate: %s\n”,strerror( errno ) );
return EXIT_FAILURE;
}
/* Map the memory object*/
addr = mmap(0,4, PROT_READ | PROT_WRITE , MAP_SHARED, fd, 0 );

if( addr == MAP_FAILED )
{
fprintf( stderr, “mmap failed: %s\n”, strerror( errno ) );
return EXIT_FAILURE;
}
And I am writing into shared memory as follows

int Write_To_Shared_Memory(int data, int location)
{
addr[location]=data;
return 0;
}
What my problem is when the location is >1023 then I am getting ‘memory fault error message’. Can any one please tell me where I am doing wrong and why this is happening

Raohansikarao,

The 2nd parameter in this call:

addr = mmap(0,4, PROT_READ | PROT_WRITE , MAP_SHARED, fd, 0 );

is meant to be the size of your shared memory region. You have it set to 4 bytes. It should be 8192.

It fails at 1023 because the smallest block QNX allocates (from memory) is 1K or 4096 bytes even if you only request 4 (in your mistake). So once you pass location 1023*4 (4 bytes per integer) you get the crash.

Tim

To add to Tim’s comment: ftruncate set the size of the object, which is an independant concept of mapping the memory to your process. You could create the object but never map it for example. And mmap can be use to map only a portion of the object ( that is what you are doing).

Thank you very much, my problem is solved now.