Shared Memory – Linux O.S


/* Program using shared memory */

#include <stdio.h>
#include <sys/shm.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>

int main()
{
key_t key1 = 1000,key2 = 2000,key3 = 3000,shmid1,shmid2,shmid3;
int *A,*B,*C,i,j,k,m,n,p,q;

shmid1=shmget(key1,100*sizeof(int),IPC_CREAT);
if(shmid1==-1)
{
printf(“\n\t ERROR : ALLOCATION FAILED \n”);
exit(0);
}

shmid2=shmget(key2,100*sizeof(int),IPC_CREAT);
if(shmid2==-1)
{
printf(“\n\t ERROR : ALLOCATION FAILED \n”);
exit(0);
}

shmid3=shmget(key3,100*sizeof(int),IPC_CREAT);
if(shmid3==-1)
{
printf(“\n\t ERROR : ALLOCATION FAILED \n”);
exit(0);
}

A = shmat(shmid1,NULL,0);
B = shmat(shmid2,NULL,0);
C = shmat(shmid3,NULL,0);

printf(“\n\t ROWS for matrix A : “);
scanf(“%d”,&m);
printf(“\n\t COLUMNS for matrix A : “);
scanf(“%d”,&n);
printf(“\n\t Enter the elements : “);
for(i = 0;i<m;i++)
for(j = 0;j<n;j++)
scanf(“%d”,(A+(n*i)+j));

printf(“\n\t MATRIX A : “);
for(i = 0;i<m;i++)
{
printf(“\n”);
for(j = 0;j<n;j++)
printf(“\t%d”,*(A+(n*i)+j));
}

printf(“\n”);

printf(“\n\t ROWS for matrix B : “);
scanf(“%d”,&p);
printf(“\n\t COLUMNS for matrix B : “);
scanf(“%d”,&q);
printf(“\n\t Enter the elements : “);
for(i = 0;i<p;i++)
for(j = 0;j<q;j++)
scanf(“%d”,(B+(q*i)+j));

printf(“\n\t MATRIX B : “);
for(i = 0;i<p;i++)
{
printf(“\n”);
for(j = 0;j<q;j++)
printf(“\t%d”,*(B+(q*i)+j));
}

if(n != p)
{
printf(“\n\n\t ERROR : MATRICES NOT COMPATIBLE FOR MULTIPLICATION \n”);
printf(“\n\t\t\t PROGRAM TERMINATED \n\n”);
exit(0);
}

for(i = 0;i<m;i++)
{
for(j = 0;j<q;j++)
{
*(C+(q*i)+j) = 0;
for(k = 0;k<n;k++)
*(C+(q*i)+j) = *(C+(q*i)+j) + (*(A+(n*i)+k)) * (*(B+(q*k)+j));
}
}

printf(“\n\t THE PRODUCT OF matrices A & B are : \n”);
for(i = 0;i<m;i++)
{
printf(“\n”);
for(j = 0;j<q;j++)
printf(“\t%d”,*(C+(q*i)+j));
}

printf(“\n\n”);

shmctl(shmid1,IPC_RMID,NULL);
shmctl(shmid2,IPC_RMID,NULL);
shmctl(shmid3,IPC_RMID,NULL);

return 0;
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s