Tutorial 4 of Parallel Processing

QUE 1) WRITE A PROGRAM TO CREATE 5 PROCESSES AND USING THAT PROCESSES COMPUTE SUM OF 10 ELEMENT BY LOOP SPLITING.

void *sharei(int size,int* shmid)
{
*shmid=shmget(IPC_PRIVATE,size,0666|IPC_CREAT);
return shmat(*shmid,0,0);
}
void cleanup_memory(int *shmid)
{
shmctl(*shmid,IPC_RMID,NULL);
}

T4p1.c:

#include<stdio.h>
int main()
{
int shmid,a[10],*sum,final_sum=0,id,i;
for(i=0;i<10;i++){
printf("Enter Element %d:",i+1);
scanf("%d",&a[i]);
}
sum=sharei(20,&shmid);
id=process_fork(5);
sum[id]=0;
for(i=id;i<10;i=i+5)
{
sum[id]+=a[i];
}
process_join(id,5);
for(i=0;i<5;i++)
{
final_sum+=sum[i];
}
printf("result=%d\n",final_sum);
cleanup_memory(&shmid);
}

OUTPUT:
[08ce55@linux ~]\$ gcc loop.c
[08ce55@linux ~]\$ ./a.out
1
2
3
4
5
6
7
8
9
10
finalsum=55

QUE 2) WRITE A PROGRAM TO FIND MINIMUM AND MAXIMUM NUMBER FROM 10 NUMBERS USING 5 PROCESSES AND LOOP SPLITTING.

#include<stdio.h>
int main()
{
int id,i,shmid,a[10],*max,finalmax,*min,finalmin;
for(i=0;i<10;i++)
scanf("%d",&a[i]);

max=sharem(20,&shmid);
min=sharem(20,&shmid);

id=process_fork(5);
max[id]=a[id];
min[id]=a[id];
for(i=id;i<10;i=i+5)
{
if(a[i]>max[id])
{
max[id]=a[i];

}
if(a[i]<min[id])
{
min[id]=a[i];

}
}
process_join(id,5);
finalmax=max[0];
finalmin=min[0];
for(i=0;i<5;i++)
{
if(max[i]>finalmax)
{
finalmax=max[i];
}
if(min[i]<finalmin)
{
finalmin=min[i];
}
}

printf("Minimum=%d\n",finalmin);
printf("Maximum=%d\n",finalmax);

shmdt((void*)max);
shmdt((void*)min);
shmctl(shmid,IPC_RMID,NULL);
}
Output:-
[08ce59@linux ~]\$ ./a.out

30
3
45
60
90
900
800
700
56
709
Minimum=3
Maximum=900