我可以在QNX上使用shm_open而不是shmget

时间:2016-01-27 04:33:29

标签: qnx

我是QNX平台的新手,我们正在将Linux项目移植到QNX。并找到与使用shmget系统调用在linux中创建共享内存相关的代码。但在QNX中没有出现。我看到类似的电话shm_open,我不知道两者的区别。

我的直接问题是,我应该在QNX平台中使用shm_open而不是shmget吗?如果有,怎么样?如果没有,为什么不呢?

1 个答案:

答案 0 :(得分:1)

首先, QNX 不支持shmget() API。

  

您需要改为使用shm_open()

以下是在线QNX文档的示例程序
这表明在 QNX 上正确使用了shm_open()

#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* addr;

    /*
     * In case the unlink code isn't executed at the end
     */
    if( argc != 1 ) {
        shm_unlink( "/bolts" );
        return EXIT_SUCCESS;
    }

    /* Create a new memory object */
    fd = shm_open( "/bolts", O_RDWR | O_CREAT, 0777 );
    if( fd == -1 ) {
        fprintf( stderr, "Open failed:%s\n",
            strerror( errno ) );
        return EXIT_FAILURE;
    }

    /* Set the memory object's size */
    if( ftruncate( fd, sizeof( *addr ) ) == -1 ) {
        fprintf( stderr, "ftruncate: %s\n",
            strerror( errno ) );
       return EXIT_FAILURE;
    }

    /* Map the memory object */
    addr = mmap( 0, sizeof( *addr ),
            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 );

    /* Write to shared memory */
    *addr = 1;

    /*
     * The memory object remains in
     * the system after the close
     */
    close( fd );

    /*
     * To remove a memory object
     * you must unlink it like a file.
     *
     * This may be done by another process.
     */
    shm_unlink( "/bolts" );

    return EXIT_SUCCESS;
}

希望这会有所帮助。

相关问题