Shared Memory...Some Questions.....



All,
I having trouble getting a simple example of a shared memory example
to work;

I have never worked with shared memory and any suggestions/code hints/
examples would be greatly appreciated.

From my reading you have to use shmget to specify that you need a
specific size of memory to be shared and then you use shmat to attach
it to a specific process.

My thinking, which is flawed, is that the child adding the 1099 to
what I believe the shared integer variable would then be "shared" to
the parent's final output of the procee id and the shared variable
( cout<<"Parent "<<getpid()<<ptheSharedIndex<<endl; ). The value
when ran for the parents final output is not 1099 but is the value
99.

int main (void)
{
int indexId = 0;

if((indexId = shmget(IPC_PRIVATE,sizeof(int),SHM_R|SHM_W))<0)
{
cout<<"ERROR: indexId ="<<indexId<<endl;
cout<<strerror(errno)<<endl;
exit (1);
}

int ptheSharedIndex;
ptheSharedIndex = (int)shmat(indexId,0,0); //attach to the current
process
ptheSharedIndex = 99;

int k = 0;
while (k<NUMBER_OF_PROCESSES) //Fire Off Processes
{
pid = 0;
k=k+1;
pid = fork();
if (pid == 0)
{break;}
}

if (pid == 0) /* child process */
{
int indexIdChild = 0;
if((indexIdChild = shmget(key,sizeof(int),SHM_R|SHM_W))<0)
{
cout<<" CHILD ERROR: indexIdChild "<<endl;
}
int ctheSharedIndex;
ctheSharedIndex = (int)shmat(indexIdChild,0,0);
*/
/* int ctheSharedIndex;
ctheSharedIndex = (int)shmat(indexId,0,0);*/
cout<<getpid()<<" "<<ptheSharedIndex<<endl;
ptheSharedIndex = 1099;
}

else /* parent */
{
sleep(8);
cout<<"Parent "<<getpid()<<ptheSharedIndex<<endl;
}

exit(0); //End Process (Main)
}

Thanks for the help,
Chris

.



Relevant Pages