#include <stdio.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
int main() {
int fd = open("/dev/zero", O_RDWR);
if (fd == -1) {
perror("open");
return 1;
}
size_t length = 4096; // 4KB
void *ptr = mmap(NULL, length, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
if (ptr == MAP_FAILED) {
perror("mmap");
close(fd);
return 1;
}
// 使用映射的内存
char *data = (char *)ptr;
data[0] = 'H';
data[1] = 'i';
data[2] = '\0';
printf("%s\n", data);
// 释放映射的内存
if (munmap(ptr, length) == -1) {
perror("munmap");
}
close(fd);
return 0;
}
内存映射代码保存一个
浙公网安备 33010602011771号