1 year ago

#307904

test-img

nick

How to mmap a class member variable?

I have a class with a member variable, I want to put the member vaiable into shared memory, so that the other process can access it.

here is my code:

pro.cpp:

#include<sys/mman.h>
#include<sys/types.h>
#include<fcntl.h>
#include<unistd.h>
#include<bits/stdc++.h>
using namespace std;

struct Data {
  int a = 0;
  void print() const { cout << a << endl; }
};

class A{
 public:
  A() {
    // i want to mmap d_ into a file, so the other process can read d_;
    int fd = open("shared_data", O_CREAT | O_RDWR | O_TRUNC, 0777);
    lseek(fd, sizeof(d_), SEEK_SET);
    write(fd,"",1);
    mmap(&d_, sizeof(d_), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);  // I want to mmap d_'s memory here
  }
  void revise_d(int v) {d_.a = v;}
 private:
  Data d_; // i want to share this in shared memory, so con.cpp can get it
};

int main() {
  A a;
  a.revise_d(3);  // in my imagination, this will revise d, and in con.cpp, it can be informed
  while(1);
}

// con.cpp

#include<sys/mman.h>
#include<sys/types.h>
#include<fcntl.h>
#include<unistd.h>
using namespace std;

struct Data {
  int a = 0;
  void print() const { cout << a << endl; }
};

int main() {
  int fd = open("shared_data", O_RDWR, 0777);
  Data* p = (Data*)mmap(NULL, sizeof(Data), PROT_READ, MAP_SHARED, fd, 0); 
  close(fd);
  std::string s;
  while (std::cin >> s && s != "quit") {
    p->print();  // i want p can get the update from pro, should be 3
    // but it is actually 0  !!!!!
  }
}

then i complied:

g++ pro.cpp -o pro
g++ con.cpp -o con

i run them as:

./pro

there is no input, pro just revise d_'s data

./con

when i type keyboard, it will output the d_'s data.

in my imaginition, the con will catch the update of d_, it should output 3.

but the result is 0, which means the update not be caught.

could you help on this? how can i shared a class's member variable?

ps. I perfer not increased memory cost, which means reuse the member variable's memory is the best choice.

c++

mmap

0 Answers

Your Answer

Accepted video resources