From 64dd81fc06afc1d3ecb796f7851e1a54309640be Mon Sep 17 00:00:00 2001 From: Imbus <> Date: Wed, 10 Sep 2025 08:38:21 +0200 Subject: [PATCH] Mmap_file --- mmap_file/.gitignore | 1 + mmap_file/Makefile | 12 ++++++++++ mmap_file/mmap_file.c | 56 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 69 insertions(+) create mode 100644 mmap_file/.gitignore create mode 100644 mmap_file/Makefile create mode 100644 mmap_file/mmap_file.c diff --git a/mmap_file/.gitignore b/mmap_file/.gitignore new file mode 100644 index 0000000..f0014c4 --- /dev/null +++ b/mmap_file/.gitignore @@ -0,0 +1 @@ +mapped.txt diff --git a/mmap_file/Makefile b/mmap_file/Makefile new file mode 100644 index 0000000..70f6219 --- /dev/null +++ b/mmap_file/Makefile @@ -0,0 +1,12 @@ +CC ?= gcc +CFLAGS ?= -Wall -O2 + +TARGET = main.elf +SRC = mmap_file.c + +$(TARGET): $(SRC) + @echo CC $@ + @$(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS) + +clean: + rm -f $(TARGET) diff --git a/mmap_file/mmap_file.c b/mmap_file/mmap_file.c new file mode 100644 index 0000000..781f05f --- /dev/null +++ b/mmap_file/mmap_file.c @@ -0,0 +1,56 @@ +#include +#include +#include +#include +#include +#include + +#define FILE_PATH "mapped.txt" +#define FILE_SIZE 4096 + +int main() { + int fd = open(FILE_PATH, O_RDWR | O_CREAT, 0644); + if (fd == -1) { + perror("open"); + return 1; + } + + /* We want some space to write */ + if (ftruncate(fd, FILE_SIZE) == -1) { + perror("ftruncate"); + close(fd); + return 1; + } + + /* NULL means we do not care where the mapping goes, anywhere in canonical memory will do + * PROT_READ/WRITE are just protection flags that allows our process rw rights + * MAP_SHARED means our (real time, or close to) changes are visible to other processes mmping the same file */ + void *file_memory = mmap(NULL, FILE_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + if (file_memory == MAP_FAILED) { + perror("mmap"); + close(fd); + return 1; + } + + const char *message = "This is written to file!"; + strncpy(file_memory, message, strlen(message) + 1); + + /* Re-truncate the file to known length, otherwise the entire buffer + * (4k, with garbage from whatever the kernel gave us) will be in the file*/ + if (ftruncate(fd, strnlen(message, FILE_SIZE + 1)) == -1) { + perror("ftruncate"); + close(fd); + return 1; + } + + printf("Mapped region content: %s\n", (char *)file_memory); + + munmap(file_memory, FILE_SIZE); + + close(fd); + + /* Optional finishing step, but i assume you want to inspect the file */ + // remove(file_path); + + return 0; +}