daily pastebin goal
16%
SHARE
TWEET

Untitled

a guest Dec 7th, 2017 48 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include<stdio.h>
  2. #include<unistd.h>
  3. #include<string.h>
  4. #include<stdlib.h>
  5.  
  6.  
  7.  
  8.  
  9.  
  10. int a[20];
  11. int n,nrp;
  12. int s=0;
  13.  
  14. void childProc(int readPipe, int writePipe) {
  15.    
  16.   int i=1, j, sum=0;
  17.   read(readPipe, &i, sizeof(int));
  18.     for(j=i*(n/nrp);j<(i+1)*(n/nrp);j++)
  19.       if(j<n)
  20.     sum=sum+a[j];
  21.   write(writePipe,&sum, sizeof(int));
  22.   exit(1);
  23. }
  24.  
  25.  
  26.  
  27. void parentProc(int readPipe, int writePipe) {
  28.   int rez,j,val;
  29.   for(j=0;j<nrp;j++)
  30.     {
  31.       write(writePipe,&j,sizeof(int));
  32.     }
  33.       for(j=0;j<nrp;j++)
  34.     {
  35.       read(readPipe, &val, sizeof(int));
  36.       s+=val;
  37.      
  38.     }
  39.       wait(2000);
  40. }
  41.  
  42. int main() {
  43.   int firstPipe[2];
  44.   int secondPipe[2];
  45.   int pid=1,i,j;
  46.  
  47.   printf("n=");scanf("%d",&n);
  48.  
  49.   for(i=0;i<n;i++)
  50.     {
  51.       printf("a[%d]=",i);
  52.       scanf("%d",&a[i]);
  53.     }
  54.   nrp=4;
  55.   if (pipe(firstPipe)) {
  56.     printf("Nu am putut crea conducta!\n");
  57.     exit(-1);
  58.   }
  59.   if (pipe(secondPipe)) {
  60.     printf("Nu am putut crea conducta!\n");
  61.     exit(-1);
  62.   }
  63.  
  64.   for(j=0;j<nrp;j++)
  65.     {
  66.       pid = fork();
  67.       if (pid) {
  68.     if (pid == -1) {
  69.       printf("Nu am reusit crearea procesului copil.\n");
  70.       exit(-1);
  71.     }
  72.      
  73.       } else {
  74.     childProc(firstPipe[0], secondPipe[1]);
  75.       }
  76.     }
  77.   parentProc(secondPipe[0], firstPipe[1]);
  78.   printf("suma: %d\n",s);
  79.  
  80.   wait(2000);
  81.   printf("Procesul principal gata!\n");
  82. }
RAW Paste Data
Top