Here is a example that maps a given file to memory using mmap
function. In this example, I didn't use fwrite
or write
function to write something into a disk file(just print contents to stdout), but the modified memory content is actually reflected on the disk file. I'm guessing that OS tracks mapped memory and writes to disk when mapped memory is modified. I'd like to know the detail of what OS does.
example.c
#include <stdio.h>
#include <sys/mman.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char *argv[]){
if(argc < 2){
printf("File path not mentioned\n");
exit(0);
}
const char *filepath = argv[1];
int fd = open(filepath, O_RDWR);
if(fd < 0){
printf("\n\"%s \" could not open\n",
filepath);
exit(1);
}
struct stat statbuf;
int err = fstat(fd, &statbuf);
if(err < 0){
printf("\n\"%s \" could not open\n",
filepath);
exit(2);
}
char *ptr = mmap(NULL,statbuf.st_size,
PROT_READ|PROT_WRITE,MAP_SHARED,
fd,0);
if(ptr == MAP_FAILED){
printf("Mapping Failed\n");
return 1;
}
close(fd);
ptr[statbuf.st_size - 2] = '@';
ssize_t n = write(1,ptr,statbuf.st_size);
if(n != statbuf.st_size){
printf("Write failed\n");
}
while(1);
}
mytext.txt
hello world!
compile and run
gcc example.c && ./a.out mytext.txt
program is not exited due to the last line and I can see the modified contents in another terminal via cat mytext.txt
hello world@
mmap
works and what the OS does, it's much to broad for this QA site. To understand it properly you need to read a lot about OS internals, and how it handles memory and files. – HarmaningLinux
tag – Cenozoic