Home
Source Codes
Engineering Colleges

Training  Reports
Seminar Reports
Placement Papers

Forums

   Computer Science / IT
   Electronics
   Electrical
   Mechanical
   Chemical
   Civil

   CAT / MBA

   GMAT / Foreign MBA
Latest Jobs

Engineering Jobs / Technical Jobs
Management Jobs

Sitemap
Terms of use

Displaying  Source Code(s)  
 

 
A Program to utilize message queue for implementing the merge sort(Socket Programming)

--------------------------------------------------------------------------------

Description : This program utilises the message queue in order to implement the merge sort program. The client sends the numbers in a batch and the server receives it. The server sorts the numbers of the batch and finally merges the batches.

/*Unix Program*/
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/wait.h>
#include<stdlib.h>
#include<stdio.h>
#define MAXLINE 1000

struct mymesg
{
long mtype;
int a[4];
};
void Merge(int a[],int mer[],int ct)
{
if(ct==0)
{
ct+=4;
for(int i=1;i<=ct;i++)
mer[i]=a[i];
}
else
{
for(int i=1;i<=4;i++)
{
int j=1;
while(a[i]>mer[j]&&j<=ct)j++;
if(j>ct)
mer[j]=a[i];
else
{
for(int k=ct;k>=j;k--)
mer[k+1]=mer[k];
mer[j]=a[i];
}
ct++;
}
}
}
int main()
{
int n,pid,mpid,sum,b[17],mer[17],num=16;
mpid=msgget(12,0666|IPC_CREAT);
system("clear");
printf("Elements are...<BR>);
for(int i=1;i<=num;i++)
{
b[i]=rand()%150;
printf("%d ",b[i]);
}
printf("
<BR>);
int i,ct=1,gmax;n=4;sum=0;gmax=4;
for(i=1;i<=n;i++)
{
struct mymesg ptr;
ptr.mtype=1;
pid=fork();
if (pid>0)
{
int k=0;
printf("Group %d: ",i);
for(int j=ct;j<=ct+gmax-1;j++)
{
ptr.a[++k]=b[j];
printf("%d ",ptr.a[k]);
}

printf("<BR>);
msgsnd(mpid,&ptr,MAXLINE,IPC_NOWAIT);
waitpid(pid,NULL,0);

msgrcv(mpid,&ptr,MAXLINE,0,IPC_NOWAIT);

printf("Sorted Sub-Group %d: ",i);
for(int j=1;j<=gmax;j++)
printf("%d ",ptr.a[j]);
printf("
<BR>);

Merge(ptr.a,mer,ct-1);

if(ct==num+1-gmax)
break;
ct+=gmax;
continue;
}
else
{
msgrcv(mpid,&ptr,MAXLINE,0,IPC_NOWAIT);

for(int j=1;j<=gmax;j++)
{
for(int k=1;k<=gmax-j;k++)
{
if(ptr.a[k]>ptr.a[k+1])
{
int t=ptr.a[k+1];
ptr.a[k+1]=ptr.a[k];
ptr.a[k]=t;
}
}
}
ptr.mtype=2;
msgsnd(mpid,&ptr,MAXLINE,IPC_NOWAIT);
exit(0);
}
}
printf("Merged Sorted Group....<BR>);
for(int i=1;i<=num;i++)
printf("%d ",mer[i]);
printf("
<BR>);
return 0;
}

 

 

 

Contribute content or training reports / feedback / Comments
job placement papers
All rights reserved © copyright 123ENG