AAE-CNAS-Labs/Topic-4-Forking-2/task_3_3.c

66 lines
1.5 KiB
C

//
// Written for Computer Networks and Systems lab classes
// AUTHOR : Sergiusz Warga
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
#include <sys/wait.h>
#define N_OF_ELEMENTS 1e6
#define N_OF_CHILDREN 10
#define SPAN (int)(N_OF_ELEMENTS/N_OF_CHILDREN)
int child_task(int * array, int start) {
int sum = 0;
for (int i = start; i < start + SPAN; ++i ) {
sum += array[i];
}
return (int)(sum/SPAN);
}
int avg(int * array) {
int sum = 0;
for (int i = 0; i < N_OF_CHILDREN; ++i) {
sum += array[i];
}
return sum/N_OF_CHILDREN;
}
int main() {
srandom(time(NULL));
int status[N_OF_CHILDREN];
int sums[N_OF_CHILDREN] = {0};
int children_pids[N_OF_CHILDREN];
int * array = malloc(N_OF_ELEMENTS * sizeof(int));
for (int i = 0; i < N_OF_ELEMENTS; ++i) {
array[i] = random() % 101;
}
pid_t pid;
for (int i = 0; i < N_OF_CHILDREN; ++i) {
pid = fork();
if (pid == -1) { // If something went wrong.
perror("Fork: ");
exit(EXIT_FAILURE);
}
if (pid == 0){ // If this is a child process.
int avg = child_task(array, (int)(i*SPAN));
exit(avg);
}
children_pids[i] = pid;
}
for (int i = 0; i < N_OF_CHILDREN; ++i) {
waitpid(children_pids[i], &status[i], 0);
sums[i] = WEXITSTATUS(status[i]);
}
printf("%d\n", avg(sums));
return 0;
}