使用 mmap 从文件中写入和读取结构

Writing and reading structs from file using mmap

我正在尝试使用 mmap 读写结构,但是我在 mmap 之后所做的更改没有保存到磁盘或没有正确加载。

这是我的代码示例,当 运行 第一次创建文件并且打印显示正确的数据时,第二次当文件已经存在时结构为空,用 0 填充。所以看起来更改没有写入文件,但我无法弄清楚原因。

#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>


typedef struct {
    int age;
    char name[128];
} person;

int main(int argc, char *argv[argc]){
    char filename [] = "data.person";
    int fd = open(filename, O_RDWR | O_CREAT , S_IRWXU);
    if (fd == -1) {
        printf("Failed to create version vector file, error is '%s'", strerror(errno));
    exit(1);
    }
    struct stat st;
    fstat(fd, &st);
    person *p;
    if (st.st_size ==  0) {
        ftruncate(fd, sizeof(person));
    p = (person *) mmap(0, sizeof(person), PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
    strcpy(p[0].name, "Hello");
    p[0].age = 10;
        msync(p, sizeof(person), MS_SYNC);
    }else{
    p = (person *) mmap(0, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
    if( p == MAP_FAILED){
        printf("mmap failed with error '%s'\n", strerror(errno));
        exit(0);
    }
    }
    printf("%s %d\n", p->name, p->age);
    munmap(p, sizeof(person));
    close(fd);
}

我的OS是manjaro 20,gcc版本是10.1

不要使用 MAP_PRIVATE 因为:

          Create a private copy-on-write mapping.  Updates to the
          mapping are not visible to other processes mapping the same
          file, and are not carried through to the underlying file.  It
          is unspecified whether changes made to the file after the
          mmap() call are visible in the mapped region.