Sample Header Ad - 728x90

Trying to understand memory-mapping with C++ in Linux environment

0 votes
1 answer
3566 views
I've been tasked at worked to explore memory mapping to see if we can utilize it. I'm trying to wrap my head around the concept and how to write the code. I've been trying out the code in the following video and blog post, but I'll go over my steps here as well so it's easy to recreate. I'm working in C++ (gcc version 11.2.0) on a Linux system https://www.youtube.com/watch?v=m7E9piHcfr4 https://bertvandenbroucke.netlify.app/2019/12/08/memory-mapping-files/ Here's my code write_mmap.cpp
#include 
#include 
#include 
#include 

int main() {
  // reading
  int file_read = open("test.dat", O_RDONLY, 0);
  // writing
  int file_write = open("test.dat", O_CREAT | O_RDWR,
                      S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
  posix_fallocate(file_write, 0, 4096);

  char *buffer = reinterpret_cast (mmap(NULL, 4096, PROT_WRITE, MAP_SHARED, file_write, 0));

  for (int i = 0; i < 4096; i++) {
    // Change each upper-case A to lowercase in the file
    if (buffer[i] == 'A') {
      buffer[i] = 'a';
    }
  }
}
And test.dat looks like this
Name,marker1,marker2,marker3,marker4
barc1,AA,AB,BB,--
barc2,AB,AA,BB,--
After running the commands
g++ write_mmap.cpp
./a.out
I see that test.dat has been changed to
Name,marker1,marker2,marker3,marker4
barc1,aa,aB,BB,--
barc2,aB,aa,BB,--
Which is what I was going for. I'm just unsure about a lot of things here Firstly, Is test.dat a memory-mapped file? I see it in the filesystem when I ls in my directory, but is it in virtual memory somewhere? If so, is there some way that I can figure out where in the virtual memory it's stored? Why is it that it was originally a text file when I wrote it, but it becomes a binary file after the script is done with it - when I open the file with nano, I see
Name,marker1,marker2,marker3,marker4
barc1,aa,aB,BB,--
barc2,aB,aa,BB,--
^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^
I'd also like to get some things cleared up about the memory mapping 1) This file is in RAM right now, right? Will any program (regardless of language used) be able to read from those portions of memory? 2) Is there some way to set "bookmarks" in this file. So that if I want the computer to start reading the file from a certain portion, I can tell it to read from address A to address B?
Asked by Many Questions (3 rep)
Feb 13, 2023, 10:38 PM
Last activity: Feb 14, 2023, 02:59 AM