使用mmap實現檔案的拷貝

2021-05-28 02:39:48 字數 2350 閱讀 6675

mmap與munmap函式介紹:

#include #include 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 #include 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

可以看到使用mmap的效能明顯高於使用read write的方式,這裡主要原因是使用mmap減少了使用者態和核心態間資料

的拷貝。

原始碼分析

/*

* author: liyangguang *

* * file: mmapcopy.c

* create date: 2011-07-04 21:02:48

* */

#include #include #include #include #include #include #include #include void

mmapcopy(int src_fd, size_t src_len, int dst_fd)

memcpy(dst_ptr, src_ptr, src_len);

munmap(src_ptr, src_len);

munmap(dst_ptr, src_len);}

int

main(int argc, char* argv)

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 *

* * file: copy.c

* create date: 2011-07-04 21:38:00

* */

#include #include #include #include #include #include #include void

copy(int src_fd, int dst_fd)

ptr = buffer;

} }int

main(int argc, char* argv)

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: */

mmap多程序拷貝檔案

include include include include include include include includeusing namespace std int main int argc,char ar stat ar 1 buf int len buf.st size 這裡必須要有讀...

利用mmap實現的乙個檔案拷貝例子

利用mmap實現的乙個檔案拷貝例子 gcc wall o3 o copy mmap copy mmap.c include stdio.h include stdlib.h include string h for memcpy include strings.h include sys mman....

使用mmap複製檔案

mmap可以將相應的檔案描述的內容對映到記憶體中,讀取記憶體就相當於讀取檔案了。下面這個例子,注意看不同的檔案使用的不同的flag。include include include include include include include include define file mode s i...