AAE-CNAS-Labs/Topic-5-Pipes/task_4_4.c

79 lines
1.8 KiB
C

//
// Written for Computer Networks and Systems lab classes
// AUTHOR : Sergiusz Warga
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#define N_OF_ELEMENTS 1e6
#define N_OF_CHILDREN 10
#define SPAN (int)(N_OF_ELEMENTS/N_OF_CHILDREN)
int child_task(double * array, int start, int pipe) {
double sum;
for (int i = start; i < start + SPAN; ++i ) {
sum += array[i];
}
write(pipe, &sum, sizeof(sum));
close(pipe);
return 0;
}
double avg(double * array) {
double sum = 0;
for (int i = 0; i < N_OF_CHILDREN; ++i) {
sum += array[i];
}
return sum/N_OF_ELEMENTS;
}
int main() {
int children_pids[N_OF_CHILDREN];
pid_t pid;
double sums[N_OF_CHILDREN] = {0};
double * array = malloc(N_OF_ELEMENTS * sizeof(double));
srandom(time(NULL));
for (int i = 0; i < N_OF_ELEMENTS; ++i) {
array[i] = 2*(double)random()/RAND_MAX - 1; // Nasty
}
int child_to_parent[N_OF_CHILDREN][2];
for (int i = 0; i < N_OF_CHILDREN; ++i) {
if (pipe(child_to_parent[i]) < 0 ){
fprintf(stderr,"Something went wrong!\n");
return -1;
}
pid = fork();
if (pid == -1) { // If something went wrong.
perror("Fork: ");
exit(EXIT_FAILURE);
}
if (pid == 0){ // If this is a child process.
child_task(array, (int)(i*SPAN), child_to_parent[i][1]);
exit(EXIT_SUCCESS);
}
children_pids[i] = pid;
}
for (int i = 0; i < N_OF_CHILDREN; ++i) {
read(child_to_parent[i][0], &sums[i], sizeof(double));
close(child_to_parent[i][0]);
}
printf("avg = %f\n", avg(sums));
return 0;
}