Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
- #include <unistd.h>
- #include <sys/types.h>
- #include <sys/wait.h>
- #define MAX_PROC 8
- #define SIZE 500
- #define READ 0
- #define WRITE 1
- static int numArr[SIZE];
- int getSum(int id) {
- int sum = 0;
- for (size_t i = id; i < SIZE; i+=MAX_PROC)
- sum += numArr[i];
- return sum;
- }
- void populateArray() {
- for (size_t i = 1; i <= SIZE; i++)
- {
- numArr[i] = i;
- }
- }
- void waitChildren() {
- pid_t child;
- while((child = wait(NULL)) > 0) {
- //printf("Child %d exited.\n", child);
- }
- }
- int main(int argc, char** argv) {
- int expected = (SIZE * (SIZE + 1)) / 2;
- pid_t child[MAX_PROC];
- int fd[2], sums[MAX_PROC], totalSum;
- if (pipe(fd) < 0) {
- perror("pipe");
- exit(EXIT_FAILURE);
- }
- populateArray();
- for (size_t i = 0; i < MAX_PROC; i++)
- {
- child[i] = fork();
- if(child[i] < 0) {
- perror("fork");
- exit(EXIT_FAILURE);
- }
- else if(child[i] == 0) {
- int sum=0;
- close(fd[READ]);
- for(int j = i; j < SIZE ;j+=MAX_PROC) {
- sum += numArr[j];
- }
- printf("The sum for process %d is %d\n",i, sum);
- write(fd[WRITE], &sum, sizeof(sum));
- exit(0);
- }
- }
- waitChildren();
- close(fd[WRITE]);
- for(int i = 0; i < MAX_PROC; i++) {
- read(fd[READ], &sums, sizeof(sums));
- }
- for (int i = 0; i < MAX_PROC; i++)
- {
- totalSum += sums[i];
- }
- printf("Expected: %d\nTotal sum = %d\n", expected, totalSum);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement