Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read Write Integer Array Into Shared Memory

The following is the READER-WRITER code for my shared memory.

Read Code-

int main(){
int shmid;
int *array;
int count = 5;
int i = 0;
key_t key = 12345;

shmid = shmget(key, count*sizeof(int), IPC_EXCL);

array = shmat(shmid, 0, SHM_RDONLY);

for(i=0; i<5; i++)
    {
        printf("\n%d---\n", array[i] );
    }

    printf("\nRead to memory succesful--\n");

    shmdt((void *) array);
    return 0;
}

Write Code-

int main()
{
int shmid;
int *array;
int count = 5;
int i = 0;
int SizeMem;
key_t key = 12345;

SizeMem = sizeof(*array)*count;

shmid = shmget(key, count*sizeof(int), IPC_CREAT);

array = (int *)shmat(shmid, 0, 0);

array = malloc(sizeof(int)*count);

for(i=0; i<5; i++)
{
    array[i] = i;
}

for(i=0; i<count; i++)
{
    printf("\n%d---\n", array[i]);
}

printf("\nWritting to memory succesful--\n");

shmdt((void *) array);

return 0;
}

After writing to the memory when I try to read, the output are garbage values. Can someone please explain what I have done wrong(The output shows all zeros) Thankyou

like image 304
Ansh David Avatar asked Jan 20 '14 06:01

Ansh David


2 Answers

In the write section, you used malloc() after getting share memory address, so it will be overwritten. You should remove the malloc() line

In the read section, the for loop should look like this

printf("\n%d---\n", array[i] );
like image 70
user2760375 Avatar answered Sep 22 '22 14:09

user2760375


Your malloc overwrites shmat's return value here.You are not writing to share memory but to the memory you just malloced.

array = (int *)shmat(shmid, 0, 0);

by delete this line.your code runs ok on my machine.

array = malloc(sizeof(int)*count);

like image 23
oyss Avatar answered Sep 22 '22 14:09

oyss