原文地址:点击打开链接
今天看csapp看到了虚拟存储器的映射以及mmap函数的用法,作为练习,使用mmap来实现文件的拷贝操作,同时与传统的文件拷贝操作进行了性能比较。
#include <unistd.h> #include <sys/mman.h> void *mmap(void *start, size_t length, int prot, int flag, int fd, off_t offset); //返回:若成功时则返回映射区域的指针,若出错则为MAP_FAILED(-1)
start: 最好从start开始的一个区域,这个是hint,具体映射结果还是要看返回结果
length: 映射区域的大小
prot: 映射区域的访问权限位 PROT_EXEC PROT_READ PROT_WRITE PROT_NONE
flags: 映射对象的类型 MAP_ANON MAP_PRIVATE MAP_SHARED
munmap函数删除映射区域
#include <unistd.h> #include <sys/mman.h> int munmap(void *start, size_t length);
分别使用了mmap函数和普通的read write实现了文件的复制拷贝,下面是通过复制50M的文件性能分析:
[yangguang@sim124 ~]$ time ./workspace/mmapcopy linux-20101214.tar.gz ./output real 0m0.100s user 0m0.034s sys 0m0.065s
[yangguang@sim124 ~]$ time ./workspace/copy linux-20101214.tar.gz ./output real 0m5.016s user 0m0.000s sys 0m0.124s
/* * Author: liyangguang <[email protected]> * http://www.yaronspace.cn/blog * * File: mmapcopy.c * Create Date: 2011-07-04 21:02:48 * */ #include <stdio.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <string.h> #include <errno.h> void mmapcopy(int src_fd, size_t src_len, int dst_fd) { void *src_ptr, *dst_ptr; src_ptr = mmap(NULL, src_len, PROT_READ, MAP_PRIVATE, src_fd, 0); dst_ptr = mmap(NULL, src_len, PROT_WRITE | PROT_READ, MAP_SHARED, dst_fd, 0); if (dst_ptr == MAP_FAILED) { printf("mmap error:%s\n", strerror(errno)); return; } memcpy(dst_ptr, src_ptr, src_len); munmap(src_ptr, src_len); munmap(dst_ptr, src_len); } int main(int argc, char* argv[]) { if (argc != 3) { printf("Usage: %s <src_file> <dst_file>\n", argv[0]); return -1; } int src_fd = open(argv[1], O_RDONLY); int dst_fd = open(argv[2], O_RDWR | O_CREAT | O_TRUNC);; struct stat stat; fstat(src_fd, &stat); truncate(argv[2], stat.st_size); mmapcopy(src_fd, stat.st_size, dst_fd); close(src_fd); close(dst_fd); return 0; }
/* * Author: liyangguang <[email protected]> * http://www.yaronspace.cn/blog * * File: copy.c * Create Date: 2011-07-04 21:38:00 * */ #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <string.h> #include <errno.h> #include <unistd.h> void copy(int src_fd, int dst_fd) { char buffer[1024*1024]; char *ptr = buffer; size_t nread, nwrite, nremain; while ((nread = read(src_fd, ptr, 1024*1024)) > 0) { nremain = nread; while (nremain > 0){ nwrite = write(dst_fd, ptr, nremain); nremain -= nwrite; ptr = ptr + nwrite; } ptr = buffer; } } int main(int argc, char* argv[]) { if (argc != 3) { printf("Usage: %s <src_file> <dst_file>\n", argv[0]); return -1; } int src_fd = open(argv[1], O_RDONLY); int dst_fd = open(argv[2], O_RDWR | O_CREAT | O_TRUNC, S_IRWXU);; copy(src_fd, dst_fd); close(src_fd); close(dst_fd); return 0; } /* vim: set ts=4 sw=4: */