Advertisement
Aodai

Untitled

Nov 4th, 2020
1,995
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.67 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4. #include <unistd.h>
  5. #include <sys/types.h>
  6. #include <sys/wait.h>
  7.  
  8. #define MAX_PROC 8
  9. #define SIZE 500
  10. #define READ 0
  11. #define WRITE 1
  12.  
  13. static int numArr[SIZE];
  14.  
  15. int getSum(int id) {
  16.   int sum = 0;
  17.   for (size_t i = id; i < SIZE; i+=MAX_PROC)
  18.     sum += numArr[i];
  19.   return sum;
  20. }
  21.  
  22.  
  23. void populateArray() {
  24.     for (size_t i = 1; i <= SIZE; i++)
  25.     {
  26.         numArr[i] = i;
  27.     }
  28. }
  29.  
  30. void waitChildren() {
  31.     pid_t child;
  32.     while((child = wait(NULL)) > 0) {
  33.         //printf("Child %d exited.\n", child);
  34.     }
  35. }
  36.  
  37. int main(int argc, char** argv) {
  38.     int expected = (SIZE * (SIZE + 1)) / 2;
  39.     pid_t child[MAX_PROC];
  40.     int fd[2], sums[MAX_PROC], totalSum;
  41.  
  42.     if (pipe(fd) < 0) {
  43.      perror("pipe");
  44.      exit(EXIT_FAILURE);
  45.     }
  46.    
  47.     populateArray();
  48.  
  49.     for (size_t i = 0; i < MAX_PROC; i++)
  50.     {
  51.         child[i] = fork();
  52.         if(child[i] < 0) {
  53.             perror("fork");
  54.             exit(EXIT_FAILURE);
  55.         }
  56.         else if(child[i] == 0) {
  57.             int sum=0;
  58.             close(fd[READ]);
  59.             for(int j = i; j < SIZE  ;j+=MAX_PROC) {  
  60.                 sum += numArr[j];  
  61.             }
  62.             printf("The sum for process %d is %d\n",i, sum);
  63.             write(fd[WRITE], &sum, sizeof(sum));
  64.             exit(0);
  65.         }
  66.     }
  67.  
  68.     waitChildren();
  69.     close(fd[WRITE]);
  70.     for(int i = 0; i < MAX_PROC; i++) {
  71.         read(fd[READ], &sums, sizeof(sums));
  72.     }
  73.  
  74.     for (int i = 0; i < MAX_PROC; i++)
  75.     {
  76.         totalSum += sums[i];
  77.     }
  78.  
  79.     printf("Expected: %d\nTotal sum = %d\n", expected, totalSum);
  80.     return 0;
  81. }
  82.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement