abstract
问:对同一个文件多次mmap,返回的地址相同吗?
答:不相同
code
#ifdef __linux__
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <errno.h>
#include <string.h>
#include <vector>
#include <stdint.h>
#include <stdio.h>
// 问:对同一个文件多次mmap,返回的地址相同吗?
// 答:不相同
void linux_mmap_test1(void)
{
const char* file = "/userdata/lxz/test/Makefile";
struct stat fileInfo = {0};
int fd = -1;
std::vector<int> fds;
std::vector<uint8_t*> ptrs;
uint8_t* ptr = nullptr;
if (stat(file, &fileInfo) != 0) {
fprintf(stderr, "stat error,%s\n", strerror(errno));
return;
}
for (int i = 0; i < 5; ++i) {
fd = open(file, O_RDONLY);
if (fd < 0) {
fprintf(stderr, "i:%d,open error,%s\n", i, strerror(errno));
break;
}
fds.push_back(fd);
ptr = (uint8_t*)mmap(nullptr, (size_t)fileInfo.st_size, PROT_READ, MAP_SHARED, fd, 0);
if (!ptr) {
fprintf(stderr, "i:%d,mmap error,%s\n", i, strerror(errno));
break;
}
fprintf(stderr, "%d <=> %llu\n", fd, (size_t)ptr);
ptrs.push_back(ptr);
}
for (size_t n = 0; n < ptrs.size(); ++n) {
if (munmap(ptrs[n], size_t(fileInfo.st_size)) != 0) {
fprintf(stderr, "n:%llu,munmap error,%s\n", n, strerror(errno));
}
}
for (size_t n = 0; n < fds.size(); ++n) {
close(fds[n]);
}
}
#endif