• Some users have recently had their accounts hijacked. It seems that the now defunct EVGA forums might have compromised your password there and seems many are using the same PW here. We would suggest you UPDATE YOUR PASSWORD and TURN ON 2FA for your account here to further secure it. None of the compromised accounts had 2FA turned on.
    Once you have enabled 2FA, your account will be updated soon to show a badge, letting other members know that you use 2FA to protect your account. This should be beneficial for everyone that uses FSFT.

Pipe help

Ephesos

n00b
Joined
Feb 26, 2011
Messages
55
Greetings everyone, I need a bit of help in solving the following problem:
I'm given an array of numbers and I have to compute the sum of the array elements using n processes, and the inter process communication has to be done with pipes(one pipe, to be exact).

I managed to solve the problem by waiting for a random child to finish, reading the sum sent by the child through the pipe, and so on for the following children, and incrementing the final sum.

Now I have to solve it by reading the partial sums in one fell swoop, after all the children have finished, and I'm not sure as to how to save the entire information sent by the kids. I tried to use a for statement, but it failed, since all the information would be passed in one single element of the array, and offering only the address of the first element in the array failed as well.

Any input would be much appreciated.

Here is the code that's bugging me:

Code:
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
 
 
 
void main () {
 
        int size, fd [2];
        printf ("enter the size of the number array: ");
        scanf ("%d", &size);
        int i, arr [size];
        for(i=0; i < size; i++)
           arr [i] = i + 1;
        
 
        int nr_proc;
        printf ("enter the number of processes that you want to use: ");
        scanf ("%d", &nr_proc);
        pid_t pid [nr_proc];
        
        for (i = 0; i < nr_proc; i++) {
           pipe (fd);
           pid [i] = fork ();
           if (pid [i] < 0)
              printf ("error in fork.\n");
           if (pid [i] == 0) {
              close (fd [0]);
              int j = 0, sum = 0;
              for (j = i * size/nr_proc; j < (i+1) * size/nr_proc; j++) {
                sum += arr[j];
              }
              printf ("test %d\n", sum);
              write(fd [1], &sum, sizeof (int));
              exit (1);
           }
        }
        close (fd [1]);
        for (i = 0; i < nr_proc; i++)
           wait ();
        int aux[nr_proc], test = 0;
        read (fd [0], aux, sizeof(aux));  // this is where i need help
        printf ("test aux %d\n", aux [1]);
        int sum = 0;
        for (i = 0; i < nr_proc; i++)
           sum += aux [i];
        printf ("result = %d\n", sum);
              
}
 
Back
Top