简体   繁体   中英

can i just mmap a file and revise it without writting 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);                                                                                                                                   
    // fd = open(argv[1], O_RDONLY, 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 dont want write back when exit the code.

I know when the code exit, it will write it back whether i call munmap or not.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM