Skip to content

Instantly share code, notes, and snippets.

@jerrinsg
Created February 19, 2021 07:49
Show Gist options
  • Save jerrinsg/1751d8e35d20376bf7ee120a343ebdeb to your computer and use it in GitHub Desktop.
Save jerrinsg/1751d8e35d20376bf7ee120a343ebdeb to your computer and use it in GitHub Desktop.
Program to map a persistent memory file
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <sys/mman.h>
#define MAP_SYNC 0x80000
#define MAP_SHARED_VALIDATE 0x03
#define FILE_LEN 1024 * 1024 // 1MB
int main() {
char *file = "/mnt/ext4-pmem0/file";
int fd = open(file, O_RDWR | O_CREAT);
if (fd < 0) {
printf("File open failed - %d\n", errno);
exit(1);
}
if (ftruncate(fd, FILE_LEN) != 0) {
printf("File truncate failed - %d\n", errno);
exit(1);
}
if (posix_fallocate(fd, 0, FILE_LEN) != 0) {
printf("posix_fallocate failed - %d\n", errno);
exit(1);
}
void *addr = mmap(NULL, FILE_LEN, PROT_READ|PROT_WRITE,
MAP_SHARED | MAP_SHARED_VALIDATE | MAP_SYNC,
fd, 0);
if (addr == MAP_FAILED) {
printf("Persistent memory map failed - %d\n", errno);
exit(1);
}
printf("Persistent memory file successfully mapped at address %p\n", addr);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment