View topic - how to create shared memory

how to create shared memory

anything that doesn't fit to other groups.

how to create shared memory

Postby raohansikarao » Wed May 05, 2010 12:09 pm

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
Active Member
 
Posts: 34
Joined: Thu Feb 25, 2010 4:25 am

Postby Tim » Wed May 05, 2010 1:20 pm

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
Tim
Senior Member
 
Posts: 1469
Joined: Wed Mar 10, 2004 12:28 am

Postby mario » Wed May 05, 2010 3:49 pm

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).
mario
QNX Master
 
Posts: 4132
Joined: Sun Sep 01, 2002 1:04 am

Postby raohansikarao » Fri May 07, 2010 9:22 am

Thank you very much, my problem is solved now.
raohansikarao
Active Member
 
Posts: 34
Joined: Thu Feb 25, 2010 4:25 am


Return to General Programming

Who is online

Users browsing this forum: No registered users and 2 guests