#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;
}

  内存映射代码保存一个

 
posted on 2024-07-15 14:02  轻于飞  阅读(16)  评论(0)    收藏  举报