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

91 lines
2.1 KiB
C
Raw Permalink Normal View History

2021-03-24 18:52:27 +01:00
//
// 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)
union floaty {
float number;
char bytes[sizeof(float)];
};
int child_task(float * array, int start) {
union floaty sum;
for (int i = start; i < start + SPAN; ++i ) {
sum.number += array[i];
}
char filename[16];
snprintf(filename, 16, "sum%d.txt", getpid());
int file = open(filename, O_CREAT | O_WRONLY);
write(file, sum.bytes, sizeof(sum));
close(file);
return 0;
}
float avg(float * array) {
float sum = 0;
for (int i = 0; i < N_OF_CHILDREN; ++i) {
sum += array[i];
}
return sum/N_OF_ELEMENTS;
}
int main() {
srandom(time(NULL));
int status[N_OF_CHILDREN];
float sums[N_OF_CHILDREN] = {0};
int children_pids[N_OF_CHILDREN];
float * array = malloc(N_OF_ELEMENTS * sizeof(float));
for (int i = 0; i < N_OF_ELEMENTS; ++i) {
array[i] = 2*(float)random()/RAND_MAX - 1; // Nasty
}
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.
child_task(array, (int)(i*SPAN));
exit(EXIT_SUCCESS);
}
children_pids[i] = pid;
}
for (int i = 0; i < N_OF_CHILDREN; ++i) {
waitpid(children_pids[i], &status[i], 0);
}
char filename[16];
union floaty sum;
for (int i = 0; i < N_OF_CHILDREN; ++i) {
sum.number = 0;
snprintf(filename, 16, "sum%d.txt", children_pids[i]);
int file = open(filename, O_RDONLY);
read(file, sum.bytes, sizeof(sum));
sums[i] = sum.number;
close(file);
}
printf("avg = %f\n", avg(sums));
return 0;
}