使用記憶體對映檔案(mmap)

轻于飞發表於2024-07-15
#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;
}

  

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

相關文章