Mmap_file
This commit is contained in:
parent
e27ef8ca49
commit
64dd81fc06
3 changed files with 69 additions and 0 deletions
1
mmap_file/.gitignore
vendored
Normal file
1
mmap_file/.gitignore
vendored
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
mapped.txt
|
||||||
12
mmap_file/Makefile
Normal file
12
mmap_file/Makefile
Normal file
|
|
@ -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)
|
||||||
56
mmap_file/mmap_file.c
Normal file
56
mmap_file/mmap_file.c
Normal file
|
|
@ -0,0 +1,56 @@
|
||||||
|
#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;
|
||||||
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue