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.