c++mmap

Can I just mmap a file and revise it without writing back?


I want to open a file in memory, and revise some elememts.

Here is the code:

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include<sys/mman.h>
#include<sys/types.h>
#include<string.h>
#include<unistd.h>

#include <iostream>
using namespace std;

int main(int argc, char *argv[]) { 
    int fd;
    if (argc < 2) { 
      printf("./app filename\n");
      exit(1);
    } 
    fd = open(argv[1], O_CREAT | O_RDWR | O_TRUNC, 0777);                                                                                                                                   
    lseek(fd, 128*sizeof(int)+1, SEEK_SET);
    write(fd, "", 1);
    int* p = (int*)mmap(NULL, 128 * sizeof(int), PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
    for (int i = 0; i < 128; ++i) { 
      *(p + i) = i;
      sleep(1);
      cout << "writing " << i << " as " << i << endl;
    } 
    close(fd);
    munmap(p, 128 * sizeof(int));
    return 0;
}

But I want to keep the file clean, which means I don't want to write back when the program exists.

I know when the program exits, it will write data back whether I call munmap or not.

So, how can I keep the file clean, and revise the element just in memory?


Solution

  • You want MAP_PRIVATE flag to mmap. It is defined as following:

    MAP_PRIVATE: Create a private copy-on-write mapping. Updates to the mapping are not visible to other processes mapping the same file, and are not carried through to the underlying file. It is unspecified whether changes made to the file after the mmap() call are visible in the mapped region.

    This means that you'll get the file, but the first time you change the file, it will create a private copy just for you. All changes will go to this copy, and will disappear once program exits.