I am currently trying the put structures in a shared memory between 2 process on linux. I have no problem sharing bool or int but when trying to share a string, std::string or char i have a segmentation fault error.
Right now my code is :
#include <iostream>
#include <sys/types.h> //shmat
#include <sys/shm.h>
#include <sys/stat.h> //open
#include <fcntl.h>
#include <unistd.h> //close
using namespace std;
struct Prises{
int numero;
int transactionId;
bool reservation;
bool charge;
bool disponibilite;
bool defaut;
bool verrouillage;
bool trappe;
int LEDverte;
int LEDrouge;
std::string carte;
std::string etat;
};
int main()
{
const char *keyFile = "/tmp/key.dat";
/* Make sure the file exists. */
int descriptor = open(keyFile, O_CREAT | O_RDWR, S_IRWXU);
/* Only wanted to make sure that the file exists. */
close(descriptor);
/* Generate memory key. */
key_t sharedKey = ftok(keyFile, 1);
/* Get the shared memory segment id. Note we include
the permissions. */
int sharedSpaceId = shmget(sharedKey, 2*sizeof(Prises),
IPC_CREAT | S_IRUSR | S_IWUSR);
/* Attach the shared memory segment. */
Prises *PrisesArray = (Prises *) shmat(sharedSpaceId, NULL, 0);
PrisesArray[1].defaut=true;
PrisesArray[2].defaut=false;
int ok;
std::cin>>ok;
return 0;
}
In this example sharing the 2 bool from the 2 structures is working well but if i try to input a data or read a data from the std::string (etat, carte) like this :
PrisesArray[1].etat="hello";
It gives me a segmentation fault in debug (and clear don't work in release), i tried with simple string and char (even one char) and it still gives me a segmentation fault.
Am i missing something when it comes to text sharing or making a mistake here ?
PrisesArray[2]accesses the array past its end.