Task 5 (20 points) In this task, you will design and implement a program to use
ID: 3572242 • Letter: T
Question
Task 5 (20 points) In this task, you will design and implement a program to use multiple processes to calculate the average of an integer array. Your program will do the following 1. Open a file named number.dat for reading (use fopenO) 2. Read the first number from that file (use fscanfo) The first number will indicate the size of the array. 3. Use mallocO to allocate space for the array. 4. Read in the array on number at a time using fscanfo 5. forkO a new process 6. The parent process will calculate the sum of the first half of the array 7. The child process will calculate the sum of the second half of the array. 8. The child will send its result to the parent using a pipeO then it will exit. 9. The parent process will receive the result and calculate the average for the whole array and print it out to standard output Name your program avearge.c. This skeleton code will fork0 a child process, the child process will send a number to the parent then the parent will print it out to standard output. Remember to close the files and free the pointer before exiting. Your program should work like this: hb 117 uxb4 gcc average c -o average hbo 11 7Quxb4 /average The average is 32716.061050 auxb4Explanation / Answer
#include<sys/types.h>
#include<errno.h>
#include<stdio.h>
#include<sys/wait.h>
#include<stdlib.h>
#include<unistd.h>
int main(void)
{
FILE *fp=fopen("number.dat","r");
int size;
int num;
int *array;
long int Sum=0,pSum=0,cSum=0;
if(fp==NULL)
{
printf("Error in opening the file ");
return 0;
}
fscanf(fp,"%d", &size);
printf("size:%d ",size);
array=malloc(sizeof(int)*size);
int i=0;
while(i<size)
{
fscanf(fp,"%d", &array[i++]);
}
fclose(fp);
for(i=0;i<size;i++)
printf("%d ",array[i]);
printf(" ");
int fds[2];
pipe(fds);
switch(fork()){
case 0: //child process
cSum=0;
for(i=size/2;i<size;i++)
cSum += array[i];
write(fds[1],&cSum,sizeof(cSum));
exit(0);
break;
case -1:
printf("Error in forking ");
break;
default:
//parent process
Sum=0;pSum=0;
for(i=0;i<size/2;i++)
Sum += array[i];
read(fds[0],&pSum,sizeof(pSum));
int status;
wait(&status);
pSum += Sum;
printf("The sum of the array is %ld ",pSum);
float avg= (float)pSum/size;
printf("The average is %f ", avg);
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.