PMDK libpmem 例程1 变量写入持久化内存

版权声明: https://blog.csdn.net/qccz123456/article/details/81877683

变量写入持久化内存
libpmem是一个低层次持久化内存的库,当需要持久化存储的时候,需要手到flush,所以通常开发者采用libpmemobj更方便。flush在linux中指的是fsync()或msync()函数。
Key:
addr pmem_map_file() // 创建持久化内存的文件,并将文件映射,得到指向文件的指针
pmem_persist() // 若地址是指向持久化内存的单一变量,则采用pmem_persist()进行持久化
pmem_msync() // 若地址指向普通易失性内存的单一变量,则采用pmem_msync()进行持久化
pmem_unmap() // 解除映射关系
单一变量指的是char *ptr、size_t、int、double等变量,非数组类型。

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <io.h>
#include <string.h>
#include <libpmem.h>

/* using 4k of pmem for this example */
#define PMEM_LEN 4096

#define PATH "/pmem-fs/myfile"  // like "/home/hostname/Desktop/pmem.001"

int main(int argc, char *argv[])
{
    char *pmemaddr;
    size_t mapped_len;
    int is_pmem;

    /* create a 4k pmem file and memory map it */
    if ((pmemaddr = pmem_map_file(PATH, PMEM_LEN, PMEM_FILE_CREATE,
                0666, &mapped_len, &is_pmem)) == NULL) {
        perror("pmem_map_file");
        exit(1);
    }

    /* store a string to the persistent memory */
    strcpy(pmemaddr, "hello, persistent memory");

    /* flush above strcpy to persistence */
    if (is_pmem)
        pmem_persist(pmemaddr, mapped_len);
    else
        pmem_msync(pmemaddr, mapped_len);

    /*
     * Delete the mappings. The region is also
     * automatically unmapped when the process is
     * terminated.
     */
    pmem_unmap(pmemaddr, mapped_len);
}

pmem_map_file()函数就相当于以下函数:

    int fd;
    char *pmemaddr;
    int is_pmem;

    /* create a pmem file */
    if ((fd = open("/pmem-fs/myfile", O_CREAT|O_RDWR, 0666)) < 0) {
        perror("open");
        exit(1);
    }

    /* allocate the pmem */
    if ((errno = posix_fallocate(fd, 0, PMEM_LEN)) != 0) {
        perror("posix_fallocate");
        exit(1);
    }

    /* memory map it */
    if ((pmemaddr = pmem_map(fd)) == NULL) {
        perror("pmem_map");
        exit(1);
    }

参考文献:http://pmem.io/pmdk/libpmem/

猜你喜欢

转载自blog.csdn.net/qccz123456/article/details/81877683