CPlay/mmap_file/mmap_file.c
2025-11-14 16:31:23 +01:00

56 lines
1.6 KiB
C

#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#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;
}