shared segment creation

hello!
i'm writing a program using shared memory segment which i want to attach to other parts of the program.the thing is that my shared memory segment is represented by a class named SharedSegment so when i create the object sharedSegment i use the constructor of the class like this:

sharedSegment = new SharedSegment ();

but when i want to attach the shared memory i have to use the following :

void *shmat(int shmid, void *shmaddr, int shmflg)

which needs the shmid..
the only way to get the shmid is by creating the shared memory with

int shmget(key t key, int size, int shmflg)

but my program creates it with the class constructor and as result i dont
have a shmid.

what should i do?
thank you
If you are calling shmget() in your ctor then just store the id as a class member. How are you creating a shared memory segment if you are not calling shmget()?
that was my question i didnt know where i should use the shmget.so you suggest i should call it
in the class constructor and then store the id as a private member right?
If the class is going to be in charge of access to the shared memory then absolutely. Even if it won't be "in charge" it would still make a clean encapsulation method.
ok thats how i did it.thanks a lot! also i'd like to ask if my main program which creates the shared segment has to attach it as well like this:

1
2
3
int* mem;
mem = (int *) shmat(shmid, (void*)0, 0);
if ((int) mem == -1) perror("Attachment.");


and the client programs have to attach it like this since sharedSegment is a class object:

1
2
3
SharedSegment sharedSegment;
sharedSegment= (int *) shmat(shmid, (void*)0, 0);
if ((int) mem == -1) perror("Attachment.");


it's a bit confusing
Hmmm, I've got different classes for encapsulating the shared memory segment depending on if the program is the parent or a child.

The class for parent programs is responsible for deleting the shared segment to recover the memory when it goes out of scope. The class used in child programs does not do this.

I am also using semaphores to lock an object in the segment for both reading and writing by parent and child processes.
Topic archived. No new replies allowed.