mmap内存映射复习
2024-10-18 05:30:06
c语言初学时,比较常见的一个习题就是实现cp。
使用c库实现的cp就不赘述了。
最近工作用到内存映射,就拿来练下手,复习一下mmap的用法。
很简单,将目标文件和源文件映射到内存,然后使用memcpy拷贝即可。
可以省去中间缓存的创建,代码页较为简单,拷贝速度也不错。
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h> #define COFYMODE 0666 int copy(const char* src, const char* dest)
{
int ret = -;
int in_fd = -, out_fd = -;
size_t filesize;
char nullbyte;
void *source_addr = NULL;
void *dest_addr = NULL; /* check args */
if(src == NULL || dest == NULL){
fprintf(stderr,"file path can not be null\n");
return ret;
} /* open files */
if((in_fd=open(src, O_RDONLY))==-) {
fprintf(stderr, "Cannot open %s\n", src);
return ret;
} #if defined(i386) || defined(__x86_64) || defined(__x86_64__) || defined(i686)
if((out_fd=open(dest, O_RDWR|O_CREAT|O_TRUNC,COFYMODE))==-)
{
fprintf(stderr, "Cannot open %s\n", dest);
ret = -;
goto cleanup;
}
#else
if((out_fd=open(dest, O_WRONLY|O_CREAT|O_TRUNC,COFYMODE))==-)
{
fprintf(stderr, "Cannot create %s\n", dest);
ret = -;
goto cleanup;
}
#endif if((filesize=lseek(in_fd,,SEEK_END))==-)
{
fprintf(stderr, "Could not seek to end of file %s\n", src);
ret = -;
goto cleanup;
} if(filesize == )
{
ret = ;
goto cleanup;
} lseek(out_fd,filesize-,SEEK_SET);
write(out_fd,&nullbyte,); /* setup the memory maps */
if((source_addr=mmap(NULL,filesize,PROT_READ,MAP_SHARED,in_fd,))==(void *)-)
{
fprintf(stderr, "Error mapping file %s\n", src);
ret = -;
goto cleanup;
} if((dest_addr=mmap(NULL,filesize,PROT_WRITE,MAP_SHARED,out_fd,))==(void *)-)
{
fprintf(stderr, "Error mapping file %s\n", dest);
ret = -;
goto cleanup;
} /* copy the input to output by doing a memcpy */
memcpy(dest_addr,source_addr,filesize); cleanup:
/*unmap the fiels */
if(source_addr) munmap(source_addr,filesize);
if(dest_addr) munmap(dest_addr,filesize); /* close the files */
if(in_fd > )close(in_fd);
if(out_fd > ) close(out_fd); return ret;
} int main(int argc, char* argv[])
{
if(argc < )
{
fprintf(stderr, "useage: %s src_file dest_file", argv[]);
return -;
} return copy(argv[], argv[]);
}
最新文章
- PAT 1045. 快速排序(25)
- xtrabackup 使用说明(续)
- 用C#实现 查看exe所加载dll列表的功能
- 当 jquery.unobtrusive-ajax.js 遇上Web API
- C# 操作Word知识汇总
- sql拷贝表结构不拷贝表数据
- WCF之可靠性
- JAVA学习-JAVA环境准备
- GridView 和 Access数据库实现数据绑定(asp.net)
- 为什么 Flask 有那么多的好评?
- 从MySQL全库备份中恢复某个库和某张表【转】
- 修复关于apache-xampp的问题:Port 443 in use by “vmware-hostd.exe”!
- thinkphp框架知识点
- Lodop某个电脑打印内容大小有问题
- python day04笔记总结
- OSGI嵌入tomcat应用服务器(gem-web)——资源下载
- mybatis generator 为数据库保留字段 转义
- Linux内核分析— —创建新进程的过程
- Centos7下Zabbix3.4至Zabbix4.0的升级步骤
- VirtualBox中出现UUID have already exists 解决方法
热门文章
- RichtextBox 行和列
- DragQueryFile
- [每日一题] 11gOCP 1z0-052 :2013-08-31 数据库的存储结构....................................................A8
- Java IO流学习总结(转)
- java的真相
- [XML] C#XMLProcess操作Xml文档的帮助类 (转载)
- android-satellite-menu
- AsyncTask理解- Day36or37
- 数据库性能高校:CPU使用过高(下)
- 【转自CSDN】深入 Microsoft.VisualBasic.Strings.StrConv 簡繁轉換