博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
内存控制函数(1)-mmap() 建立内存映射
阅读量:7097 次
发布时间:2019-06-28

本文共 2532 字,大约阅读时间需要 8 分钟。

示例1:

1.首先建立一个文本文件,名字为tmp,内容为hello world

2.编写mmap.c

#include 
#include
#include
#include
#include
#include
#include
int main(){ int fd, len; int *p; fd = open("tmp", O_RDWR); if (fd < 0) { perror("open"); exit(1); } len = lseek(fd, 0, SEEK_END); // 第一个参数代表内存起始地址,设为NULL代表让系统自动选定地址 p = mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (p == MAP_FAILED) { perror("mmap"); exit(1); } // 如果映射成功,修改p[0] p[0] = 0x30313233; close(fd); // 释放内存映射地址 munmap(p, len); return 0;}

3.运行,并查看tmp内容

od -tx1 -tc tmp

0000000 33 32 31 30 6f 20 77 6f 72 6c 64 0a

3 2 1 0 o w o r l d \n
0000014

磁盘文件tmp的内容已被修改.

 

示例2:利用mmap实现进程间通信

process_mmap_w.c

/* process_mmap_w.c */#include 
#include
#include
#include
#include
#include
#include
#define MAPLEN 0X1000struct STU { int id; char name[20]; char sex;};void sys_error(char *str, int exitno){ perror(str); exit(exitno);}int main(int argc, char *argv[]){ struct STU *mm; int fd, i = 0; if(argc < 2) { printf("Need filename! \n"); exit(1); } fd = open(argv[1], O_RDWR | O_CREAT, 0777); if (fd < 0) sys_error("open", 1); if (lseek(fd, MAPLEN-1, SEEK_SET) < 0) sys_error("lseek", 3); if (write(fd, "\0", 1) < 0) sys_error("write", 4); mm = mmap(NULL, MAPLEN, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); if (mm == MAP_FAILED) sys_error("mmap", 2); close(fd); while(1) { mm->id = i; sprintf(mm->name, "zhang-%d", i); if (i%2 == 0) mm->sex = 'm'; else mm->sex = 'w'; i++; sleep(1); } munmap(mm, MAPLEN); return 0;}

process_mmap_r.c

#include 
#include
#include
#include
#include
#include
#include
#define MAPLEN 0x1000struct STU { int id; char name[20]; char sex;};void sys_err(char *str, int exitno){ perror(str); exit(exitno);}int main(int argc, char *argv[]){ int fd; struct STU *mm; if (argc < 2) { printf("Need input filename\n"); exit(1); } fd = open(argv[1], O_RDWR); if (fd < 0) sys_err("open", 1); mm = mmap(NULL, MAPLEN, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); if (mm == MAP_FAILED) sys_err("mmap", 2); close(fd); unlink(argv[1]); while(1) { printf("%d\n", mm->id); printf("%s\n", mm->name); printf("%c\n", mm->sex); sleep(1); } munmap(mm, MAPLEN); return 0;}

运行两个进程:

10

zhang-10
m
11
zhang-11
w
12
zhang-12
m
13
zhang-13
w
14
zhang-14
m

 

转载地址:http://qghql.baihongyu.com/

你可能感兴趣的文章
CSS3教程:pointer-events属性值详解
查看>>
[Android Pro] 告别编译运行 ---- Android Studio 2.0 Preview发布Instant Run功能
查看>>
[Web 前端] webstorm 快速搭建react项目
查看>>
阿里巴巴实习 面试题
查看>>
洛谷 P1443 马的遍历
查看>>
Asp.net MVC3 中,动态添加filter
查看>>
人民币主动贬值 你的理财方式主动调整了吗?加上外币兑换的费用,也远不如投资人民币理财产品带来的收益高...
查看>>
m6-第11周作业
查看>>
JMeter 功能挖掘之 WEB 文件导出
查看>>
Java中线程池的介绍
查看>>
js之滚动置顶效果
查看>>
algorithms第四版学习进程(一)背包,栈,队列
查看>>
HTML(五)选择器--伪类选择器
查看>>
Postgresql pg_dump
查看>>
ebtables
查看>>
Bulk Load-HBase数据导入最佳实践
查看>>
java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.util.Map
查看>>
ResultSet转成java类对象
查看>>
拟人拟物法求解不等圆Packing问题
查看>>
斐波那契堆
查看>>