加入收藏 | 设为首页 | 会员中心 | 我要投稿 衡阳站长网 (https://www.0734zz.cn/)- 数据集成、设备管理、备份、数据加密、智能搜索!
当前位置: 首页 > 服务器 > 搭建环境 > Linux > 正文

Linux系统编程中的共享内存之mmap

发布时间:2021-05-30 01:15:08 所属栏目:Linux 来源:互联网
导读:mmap函数 函数原型: voidmmap(voidadrr,size_tlength,intprot,intflags,intfd,off_toffset); 返回值: 成功:返回创建的映射区首地址; 失败:返回MAP_FAILED 具
副标题[/!--empirenews.page--]

void mmap(void adrr, size_t length, int prot, int flags, int fd, off_t offset); 

返回值:

成功:返回创建的映射区首地址;

失败:返回MAP_FAILED

具体参数含义:

addr:指向映射区的首地址,这是由系统内核所决定的,一般设为NULL;

length:欲创建的映射区大小;

prot:映射区的权限,一般有如下几种:

PROT_EXEC 映射区域可被执行

PROT_READ 映射区域可被读取

PROT_WRITE 映射区域可被写入

PROT_NONE 映射区域不能存取

flags:指映射区的标志位,MAP_FIXED与MAP_PRIVATE必须选择一个:

MAP_FIXED:对映射区所作的修改会反映到物理设备,但需要调用msync()或者munmap();

MAP_PRIVATE:对映射区所作的修改不会反映到物理设备。

fd:创建的映射区的文件描述符;

offset:被映射文件的偏移量,一般设为0,表示从头开始映射。

mumap函数

函数原型:

int munmap(void *addr, size_t length); 

函数作用:

如同malloc之后需要free一样,mmap调用创建的映射区使用完毕之后,需要调用munmap去释放。

例程

写进程:

 #include <stdio.h> 

 #include <sys/mman.h> 

 #include <sys/types.h> 

 #include <sys/stat.h> 

 #include <fcntl.h> 

 #include <unistd.h> 

 #include <string.h> 

  

 typedef struct 

{11    int id; 

    char name[20]; 

    char gender; 

}stu; 

 

int main(int argc, char *argv[]) 

    stu *p = NULL; 

    int fd = 0; 

    stu student = {10, "harry", 'm'}; 

 

   if (argc < 2) { 

        printf("useage: ./a.out filen"); 

        return -1; 

    } 

 

    fd = open(argv[1], O_RDWR | O_CREAT, 0664); 

    if (fd == -1) { 

        printf("ERROR: open failed!n"); 

        return -1; 

    } 

    ftruncate(fd, sizeof(stu)); 

 

    p = mmap(NULL, sizeof(stu), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); 

    if (p == MAP_FAILED) { 

        printf("ERROR: mmap failed!n"); 

        return -1; 

    } 

 

    close(fd); 

 

    while (1) { 

        memcpy(p, &student, sizeof(stu)); 

        student.id++; 

        sleep(2); 

    } 

    munmap(p, sizeof(stu)); 

 

    return 0; 

读进程:

 #include <stdio.h> 

 #include <sys/mman.h> 

 #include <sys/types.h> 

 #include <sys/stat.h> 

 #include <fcntl.h> 

 #include <unistd.h> 

  

 typedef struct 

 { 

    int id; 

    char name[20]; 

    char gender; 

}stu; 

 

int main(int argc, char *argv[]) 

    stu *p = NULL; 

    int fd = 0; 

 

    if (argc < 2) { 

        printf("useage: ./a.out filen"); 

        return -1; 

    } 

 

    fd = open(argv[1], O_RDONLY); 

    if (fd == -1) { 

        printf("ERROR: open failed!n"); 

        return -1; 

    } 

 

    p = mmap(NULL, sizeof(stu), PROT_READ, MAP_SHARED, fd, 0); 

    if (p == MAP_FAILED) { 

        printf("ERROR: mmap failed!n"); 

        return -1; 

    } 

 

    close(fd); 

 

    while (1) { 

(编辑:衡阳站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

热点阅读