Hey am trying to create a shared object between 2 processes.and trying to read and change the values from each one of them.This s my simple struct.
EDIT: I added a constructor to my struct.
struct shared{
shared(){
value = 10;
name = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
}
int value;
string name;
};
I tried both to call shmat() before and after calling fork() but nothing change it still give segmentation fault.
EDIT:And added a check after the shmat() to see if it failed.
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <iostream>
#include <sys/shm.h>
#include <string.h>
using namespace std;
struct shared{
shared(){
value = 10;
name = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
}
int value;
string name;
};
int main(){
int shm_id = shmget(IPC_PRIVATE,sizeof(shared),0);
if(shm_id == -1){
cout<<"shmget() failed "<<endl;
return -1;
}
pid_t pid = fork();
if(pid == -1){
cout<<"fork() failed "<<endl;
return -2;
}
shared* sharedPtr = (shared*)shmat(shm_id,0,0);
if(sharedPtr == 0){
cout<<"shmat() failed "<<endl;
}
cout<<"Setting up the object: "<<endl;
sharedPtr->value = 5;
sharedPtr->name = "aaaaaa: ";
if(pid == 0){ //Child process
cout<<"Child process: "<<endl;
sharedPtr->value = 10;
sharedPtr->name = "bbbbbbb: ";
cout<<"Changed the object "<<endl;
return 0;
}
if(pid != 0){ //Parent process
sleep(1);
cout<<"Parent process: "<<endl;
cout<< sharedPtr->name << sharedPtr->value<<endl;
}
return 0;
}
But I still get a segmentation fault.
std::stringin shared memory. This is guaranteed to break. And you access it from different process without any synchronisation. This cannot possibly work either. The entire approach is deeply flawed.stringwas initialised, you would have problems. While the string object itself is in shared memory, it uses memory outside its own object (for storage of the string characters). They won't be inside the shared memory. You cannot in general put a non-POD object in shared memory and expect it to work.shmatwith a null pointer). A possible solution is to use an allocator based on the shared memory segment, and to store offsets instead of pointers. Butstringor the standard containers don't support that, so – a lot of work.