How to change non-PoD fields when using shared memory? I understand that for PoD types, a similar approach "in the forehead" works and on the field allocated in mmap, the class field changes. However, the string field in this case will remain unchanged. How can it be changed? Ps The question is purely educational, so if you let some theoretical base answer - it will be great.
UPD: no PoD field remains unchanged in the parent process. In the child process, it does change, but it raises even more questions :)
#include <iostream> #include <stdio.h> #include <stdlib.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <string.h> using namespace std; class human { public: string name; int age; human() { name = '\0'; age = 0; } ~human() {} void set() { cout << "Enter name" << endl; cin >> name; cout << "Enter age" << endl; cin >> age; } void print() { cout << name << " " << age << endl; } }; main(int argc, char * argv[]) { pid_t cpid; char buf; human* shared; human non; shared = (human*)mmap(NULL, sizeof(*shared), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0); *shared = non; cpid = fork(); // duplicate the current process if (cpid == 0) // if I am the child then { shared->set(); exit(EXIT_SUCCESS); } else // if I am the parent then { wait(NULL); // wait for the child process to exit before I do the same cout << "Human:" << endl; shared->print(); exit(EXIT_SUCCESS); } return 0; }
HumanChild: Enter name qqt Enter age 123 Human: 123. For the compiler do not care pod or not pod, in this case. Plus, because you understand sitting. Also do not cast in a sishny style - I'm talking about(human*)- strangeqargo