Advertisement
m4ly

MOSIX Zadanie 2

Jun 5th, 2014
490
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.92 KB | None | 0 0
  1. /**
  2. Dawid Mocek
  3. Sekcja 1
  4.  
  5. MOSIX Zadanie 2.
  6. Obliczyć sumę ciągu podanego wzorem. Liczba elementów ciągu wynosi n. W zadaniu należy stworzyć
  7. potok i k procesów potomnych. Liczby n oraz k są podawane jako parametry wywołania programu.
  8. W procesach potomnych należy obliczyć sumy częściowe, po czym wysłać wyniki do procesu rodzica,
  9. który powinien je odebrać, scalić i wyświetlić na ekranie.
  10.        
  11.      ___N___
  12.     \       |
  13.    S =   \       (i^2 - 12)^3 / ((n^3)*(i^3))
  14.      / 
  15.     /_______|
  16.        i=1
  17. */
  18. #include <stdlib.h>
  19. #include <stdio.h>
  20.  
  21. double equation(unsigned int i, unsigned int n) {
  22.     int x = (n * n * n);
  23.     int y = ((i * i) - 12);
  24.     int gora = y * y * y;
  25.     int dol = x * i * i * i;
  26.  
  27.     return (double)gora/(double)dol;
  28. }
  29.  
  30.  
  31. int main(int argc, char **argv)
  32. {
  33.  
  34.     // Liczba elemntow
  35.     int n = atoi(argv[1]);
  36.  
  37.     // Liczba procesow
  38.     int k = atoi(argv[2]);
  39.  
  40.     int i = 1;
  41.     int j = 0;
  42.  
  43.     double suma = 0, e = 0, tmp = 0;
  44.  
  45.  
  46.     int pipefd[2];
  47.     pid_t pid;
  48.  
  49.     if(pipe(pipefd) == -1) {
  50.         perror("Pipefd error\n");
  51.         exit(EXIT_FAILURE);
  52.     }
  53.  
  54.     while(i <= n) {
  55.         for(j = 0; j < k; j++) {
  56.             if(i > n)
  57.                  break;
  58.  
  59.             pid = fork();
  60.  
  61.             if(pid == -1) {
  62.                 perror("fork");
  63.                 exit(EXIT_FAILURE);
  64.             }
  65.  
  66.             if(pid == 0) {
  67.                 // printf("equation(%d,%d) = %f(pid=%d)\n", i, n, equation(i, n) , (int)getpid());
  68.                 e = equation(i, n);
  69.                 write(pipefd[1], &e, sizeof(double));
  70.                 exit(EXIT_SUCCESS);
  71.             }
  72.             else {
  73.                 // printf("parent process(pid=%d)\n", (int)getpid());
  74.             }
  75.  
  76.         i++;
  77.  
  78.         }
  79.     }
  80.  
  81.     close(pipefd[1]);
  82.  
  83.     while(read(pipefd[0], &tmp, sizeof(double)))
  84.             suma += tmp;
  85.  
  86.     printf("Suma: %f\n", suma);
  87.  
  88.     return EXIT_SUCCESS;
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement