【发布时间】:2011-07-04 18:37:08
【问题描述】:
以下是我用于在 ubuntu 中使用大页映射文件的代码,但此调用失败并出现错误“无效参数”。但是,当我通过 mmap 中没有文件描述符参数的 MAP_ANON 标志,那么它可以工作。我无法理解这背后的可能原因。
其次,当此标志本身意味着不会将任何更改写回文件时,我无法理解为什么使用 MAP_PRIVATE 允许文件映射。这总是可以使用 MAP_ANON 来完成,还是我遗漏了什么?
有人可以帮我解决这些问题吗?
int32_t main(int32_t argc, char** argv) {
int32_t map_length = 16*1024*1024; // 16 MB , huge page size is 2 MB
int32_t protection = PROT_READ | PROT_WRITE;
int32_t flags = MAP_SHARED | MAP_HUGETLB;
int32_t file__ = open("test",O_RDWR|O_CREAT | O_LARGEFILE,s_IRWXU | S_IRGRP | S_IROTH);
if(file__ < 0 ) {
std::cerr << "Unable to open file\n";
return -1;
}
if (ftruncate(file__, map_length) < 0) {
std::cerr
<< "main :: unable to truncate the file\n"
<< "main :: " << strerror(errno) << "\n"
<< "main :: error number is " << errno << "\n";
return -1;
}
void *addr= mmap(NULL, map_length, protection, flags, file__, 0);
if (addr == MAP_FAILED) {
perror("mmap");
return -1;
}
const char* msg = "Hello World\n";
int32_t len = strlen(msg);
memcpy(addr,msg,len);
munmap(addr, map_length);
close(file__);
return 0;
}
【问题讨论】:
-
int32_t main是一个错误。根据 C++ 标准,main的返回类型和argc的类型都应该只是int。 -
larsmans,这会影响程序的输出吗?在我的架构上,int 与 int32_t 相同,所以它根本不重要。但从标准的角度来看,我同意这是不对的。 (之前我在写这篇评论时犯了一些错误)
-
法拉兹:不,他只是在吹毛求疵。
-
为什么还要使用 10.04?