POSIX之Shared Memory Object

2022-06-30 18:58:36 浏览数 (2)

VxWorks支持POSIX的shared memory object - 通过shm_open()获得文件描述符,然后使用mmap()进行映射。shared和private方式都支持。

以Vx69为例,在VIP中包含组件INCLUDE_POSIX_SHM_API,VxWorks会创建一个名字为"/shm"的虚拟文件系统。这个文件系统,不支持常见的读写操作,只支持shm_open()和shm_unlink()

代码语言:javascript复制
/* establishes a connection between a shared memory object and a file descriptor */
int shm_open(char *name, int oflag, mode_t mode);
/* remove a shared memory object */
int shm_unlink(char *name);

name的格式为"/shm/xxx"或者"/xxx"

oflag可用以下选项

代码语言:javascript复制
O_RDONLY
O_RDWR
O_CREAT
O_EXCL  /* check for the existence of the object with O_CREAT */
O_TRUNC /* truncate the object to zero length with O_RDWR */

mode可用以下选项

代码语言:javascript复制
S_IRUSR /* read permission, owner */
S_IWUSR /* write permission, owner */
S_IXUSR /* execute/search permission, owner */
S_IRWXU /* read/write/execute permission, owner */

S_IRGRP /* read permission, group */
S_IWGRP /* write permission, group */
S_IXGRP /* execute/search permission, group */
S_IRWXG /* read/write/execute permission, group */

S_IROTH /* read permission, other */
S_IWOTH /* write permission, other */
S_IXOTH /* execute/search permission, other */
S_IRWXO /* read/write/execute permission, other */

使用比较简单,直接跑个例子

代码语言:javascript复制
#include <stdio.h>    /* printf() */
#include <unistd.h>   /* ftruncate() */
#include <fcntl.h>    /* O_CREAT */
#include <sys/stat.h> /* S_IRUSR */
#include <sys/mman.h> /* mmap() */

/*
 * Producer: fill object with some data.
 */
void testMemShmWrite()
{
    int  fd;
    int  ix;
    int *pData;
    
    /* 创建SHM */
    fd = shm_open("/myshm", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
    if(fd == -1)
        {
        printf("shm_open errorn");
        return;
        }

    /* 设置SHM长度 */
    if(ftruncate(fd, 0x1000) == -1)
        {
        printf("ftruncate errorn");
        close(fd);
        return;
        }

    /* 映射SHM到当前进程 */
    pData = (int *)mmap(0, 0x1000, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);

    /* 关闭fd; 不影响映射 */
    close(fd);

    if(pData == (int *)MAP_FAILED)
        {
        return;
        }

    /* 修改SHM内容 */
    for(ix = 0; ix < 25; ix  )
        *(pData   ix) = ix;

    /* 取消映射 */
    munmap((void *)pData, 0x1000);
    }

/*
 * read object data.
 */
void testMemShmRead()
{
    int  fd;
    int  ix;
    int *pData;

    /* 创建SHM */
    fd = shm_open("/myshm", O_RDWR, S_IRUSR | S_IWUSR);
    if(fd == -1)
        {
        printf("shm_open errorn");
        return;
        }

    /* 映射SHM到当前进程 */
    pData = (int *)mmap(0, 0x1000, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);

    /* 关闭fd; 不影响映射 */
    close(fd);

    if(pData == (int *)MAP_FAILED)
        {
        return;
        }

    /* 读取SHM内容 */
    for(ix = 0; ix < 25; ix  )
        printf("%d ", *(pData   ix));

    /* 从shmFs删除 */

    shm_unlink("/myshm");

    /* 取消映射 */
    munmap((void *)pData, 0x1000);
    }

0 人点赞