QNX Share Memory Sample code

Process A

#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <limits.h>
#include <sys/mman.h>
int main(int argc, char *argv[]) {
    int fd;
    unsigned char version[20];
    unsigned char * addr;


    /* Create a new memory object */
    fd = shm_open( "/version", O_RDONLY, 0777 );
    if( fd == -1 ) {
        printf("Open failed:%s\n","/version");
        return EXIT_FAILURE;
    }

    /* Map the memory object */
    addr = mmap( 0, 20,
            PROT_READ,
            MAP_SHARED, fd, 0 );
    if( addr == MAP_FAILED ) {
        printf("mmap failed\n");
        return EXIT_FAILURE;
    }

    printf( "Map addr is 0x%08x\n", addr);

    /* READ shared memory */
    memcpy(version, addr, 20);
    

    printf("version: %c%c%c%c%c%c\n", version[0], version[1], \
            version[2], version[3], version[4], version[5]);
    /*
     * The memory object remains in
     * the system after the close
     */
    close( fd );

    return EXIT_SUCCESS;
}


Process B:


#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <limits.h>
#include <sys/mman.h>
int main(int argc, char *argv[]) {
    int fd;
    unsigned char version[20];
    unsigned char * addr;


    /* Create a new memory object */
    fd = shm_open( "/version", O_RDONLY, 0777 );
    if( fd == -1 ) {
        printf("Open failed:%s\n","/version");
        return EXIT_FAILURE;
    }

    /* Map the memory object */
    addr = mmap( 0, 20,
            PROT_READ,
            MAP_SHARED, fd, 0 );
    if( addr == MAP_FAILED ) {
        printf("mmap failed\n");
        return EXIT_FAILURE;
    }

    printf( "Map addr is 0x%08x\n", addr);

    /* READ shared memory */
    memcpy(version, addr, 20);

    version[19]='\0';


    printf("version: %c%c%c%c%c%c\n", version[0], version[1], \
            version[2], version[3], version[4], version[5]);

    printf("%s\n",version);
    /*
     * The memory object remains in
     * the system after the close
     */
    close( fd );

    return EXIT_SUCCESS;
}

運行結果

標題

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章