09.11.09
Shared memory in QNX

Hi everybody!! I give you an example how to use shared memory in QNX using mmap.
First we are going to set our data structure.
#include stdio.h
#include string.h
#include fcntl.h
#include errno.h
#include stdlib.h
#include unistd.h
#include limits.h
#include sys/mman.htypedef struct{
int a;
int b;
}s_t;int main( int argc, char** argv )
{
int fd;
s_t *addr;addr = calloc(2, sizeof(s_t));
fd = shm_open( "/mi_memoria", O_RDWR | O_CREAT, 0777 );
if( fd == -1 ) {
fprintf( stderr, "Open failed:%s\n", strerror( errno ) );
return EXIT_FAILURE;
}if( ftruncate( fd, (size_t)(sizeof( addr )*2) ) == -1 ) {
fprintf( stderr, "ftruncate: %s\n", strerror( errno ) );
return EXIT_FAILURE;
}addr = mmap( 0, (size_t)(sizeof( addr )*2) , PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0 );
if( addr == MAP_FAILED ) {
fprintf( stderr, "mmap failed: %s\n", strerror( errno ) );
return EXIT_FAILURE;
}printf( "Map addr is 0x%08x\n", addr );
addr[0].a = 1;
addr[0].b = 2;
addr[1].a = 3;
addr[1].b = 4;close( fd );
return EXIT_SUCCESS;
}
So…. we are going to read or write our shared memory with the same code minus the O_CREAT FLAG at open the file descriptor with the memry path
#include
#include stdio.h
#include string.h
#include fcntl.h
#include errno.h
#include stdlib.h
#include unistd.h
#include limits.h
#include sys/mman.htypedef struct{
int a;
int b;
}s_t;int main( int argc, char** argv )
{
int fd;
s_t *addr = NULL;addr = calloc(2, sizeof(s_t));
fd = shm_open( "/mi_memoria", O_RDWR, 0777 );
if( fd == -1 ) {
fprintf( stderr, "Open failed:%s\n", strerror( errno ) );
return EXIT_FAILURE;
}if( ftruncate( fd, (size_t)(sizeof( addr )*2) ) == -1 ) {
fprintf( stderr, "ftruncate: %s\n", strerror( errno ) );
return EXIT_FAILURE;
}addr = mmap( 0, (size_t)(sizeof( addr )*2) , PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0 );
if( addr == MAP_FAILED ) {
fprintf( stderr, "mmap failed: %s\n", strerror( errno ) );
return EXIT_FAILURE;
}while(addr->a != NULL){
printf( "Map addr is 0x%08x\n", addr );
printf( "Map value a %d \n", addr->a );
printf( "Map value b %d \n", addr->b );
addr++;
}close( fd );
return EXIT_SUCCESS;
}
And wala!!!!!! This code can save you a redundant data storage or I don’t know that you have to know what jejeje. Bye!











