檔案對映操作類的實現

2021-10-07 15:13:01 字數 3417 閱讀 2810

mmap_file_op.h:

#ifndef qiniu_largefile_mmapfile_op_h_

#define qiniu_largefile_mmapfile_op_h_

#include

"common.h"

#include

"file_op.h"

#include

"mmap_file.h"

namespace qiniu

~mmapfileoperation()

}int

mmap_file

(const mmapoption& mmap_option)

;int

munmap_file()

;int

pread_file

(char

*buf,

const int32_t size,

const int64_t offset)

;int

pwrite_file

(const

char

* buf,

const int32_t sized,

const int64_t offset)

;void

*get_map_data()

const

;int

flush_file()

;

private:

mmapfile *map_file_;};

}}#endif

//qiniu_largefile_mmapfile_op_h_

mmap_file_op.cpp:

#include

"mmap_file_op.h"

#include

"common.h"

//#include "file_op.h"

//#include "mmap_file.h"

static

int debug =1;

namespace qiniu

if(mmap_option.max_mmap_size_ <=0)

int fd =

check_file()

;if(fd <0)

if(map_file_ = new mmapfile

(mmap_option, fd)

;map_file

(true);}

ifelse

}int mmapfileoperation:

:munmap_file()

return tfs_success;

}void

*mmapfileoperation:

:get_map_data()

const

return

null;}

int mmapfileoperation:

:pread_file

(char

*buf,

const int32_t size,

const int64_t offset)

if(offset + size)

<=map_file_->

get_size()

)//情況2,記憶體沒有對映或是要讀取的資料對映不全

return fileoperation:

:pread_file

(buf, size, offset);}

int mmapfileoperation:

:pwrite_file

(const

char

* buf,

const int32_t size,

const int64_t offset)

if(offset + size)

<=map_file_->

get_size()

)//情況2,記憶體沒有對映或是要寫入的資料對映不全

return fileoperation:

:pwrite_file

(buf, size, offset);}

int mmapfileoperation:

:flush_file()

else

}return fileoperation:

:flush_file()

;}}}

test.cpp:

#include

"mmap_file_op.h"

#include

using namespace std;

using namespace qiniu;

const

static largefile:

:mmapoption mmap_option=

;//記憶體對映的引數

intmain

(void)

ret = mmfo->

mmap_file

(mmap_option);if

(ret == largefile:

:tfs_error)

char buffer[

128+1]

;memset

(buffer,

'6',

128)

; buffer[

127]

='\n';

ret = mmfo->

pwrite_file

(buffer,

128,8)

;if(ret <0)

else

}memset

(buffer,0,

128)

; ret = mmfo->

pread_file

(buffer,

128,8)

;if(ret <0)

else

}else

ret = mmfo->

flush_file()

;if(ret == largefile:

:tfs_error)

memset

(buffer,

'8',

128)

; buffer[

127]

='\n'

; ret = mmfo->

pwrite_file

(buffer,

128,

4000);

// 即使這裡的偏移量很大,也會自動擴充檔案的

mmfo->

munmap_file()

; mmfo->

close_file()

;return0;

}

記憶體對映檔案操作相關

ats4demodlg.h header file if defined afx ats4demodlg h 32e6642d 5f67 4613 b312 9c160914a930 included define afx ats4demodlg h 32e6642d 5f67 4613 b312 ...

檔案對映,共享記憶體的實現

檔案對映 mmap 實際上是乙個vma的建立過程,分配程序線性區來對映開啟的檔案,把對檔案的讀寫轉為對記憶體的讀寫,在頻繁移動指標讀寫檔案的時候,讀寫效率有很大的提高。mmap 函式會呼叫特定檔案系統的mmap 全部執行之後,線性區結構vm area struct的vm file指向對映檔案的檔案物...

檔案對映實現程序通訊

需要用到兩個重要的api 1.handle hfile 2.1 security attributes 它指明返回的控制代碼是否可以被子程序所繼承,指定乙個安全物件,在建立檔案對映時使用。2.2 null 用byval as long傳遞零 表示使用預設安全物件。3.dword flprotect ...