我可以只映射一个文件并修改它而不回写吗?

can i just mmap a file and revise it without writting back?

我想在内存中打开一个文件,修改一些元素。

代码如下:

#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;
}

但我想保持文件干净,这意味着我不想在退出代码时回写。

我知道当代码退出时,无论我是否调用 munmap,它都会将其写回。

那么,我怎样才能保持文件干净,并修改内存中的元素呢?

你想要 MAP_PRIVATE 标记到 mmap。定义如下:

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.

这意味着您将获得文件,但在您第一次更改文件时,它会为您创建一个私人副本。所有更改都将转到此副本,并在程序退出后消失。