Below is the code that I use for mmaping file in ubuntu with huge pages, but this call fails with the error "invalid argument". However, when I passed the MAP_ANON flag without the file descriptor parameter in mmap, then it works. I can not understand the possible reason for this.
Secondly, I cannot understand why the mmaping file is resolved using MAP_PRIVATE, when this flag itself means that no changes will be written back to the file. Can this always be accomplished with MAP_ANON, or is there something I can't see?
Can someone help me with this?
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; }
Faraz source share