This program should calculate the value of 2^1+2^2 + … + 2^10:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <stdbool.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <math.h>
#define N 10
// sommatoria per i che va da 1 a N di 2^i, ogni processo calcola un singolo valore
int main(int argc, char** argv)
{
pid_t figli[N];
unsigned int i;
int status;
int fd[N][2];
int msg1=0,msg2;
int risultato=0;
bool padre=true;
for(i=0;i<N && padre;i++)
{
pipe(fd[i]);
figli[i]=fork();
if(figli[i]<0)
{
fprintf(stderr,"Una fork ha fallito\n");
}
else if(figli[i]==0)
{
padre=false;
}
else
{
msg1=i+1;
write(fd[i][1],&msg1,sizeof(int));
}
}
if(!padre)
{
read(fd[i][0],&msg2,sizeof(int));
msg2=pow(2.0,msg2);
write(fd[i][1],&msg2,sizeof(int));
exit(0);
}
else
{
for(i=0;i<N;i++)
{
read(fd[i][0],&msg2,sizeof(int));
risultato+=msg2;
}
}
if(padre)
fprintf(stderr,"%d\n",risultato);
return 0;
}
But when ie xecute the program, the father process prints 55.
Why?
Interestingly enough, 55 is the sum of all the numbers from 1 to 10: that should give you an instant clue:
Note that well: unidirectional. In other words, the padre is reading back the same values it wrote (hence the 55).
You normally set up two pipes for bi-directional traffic, one for each direction. So I’ve double the number of pipes, using even ones for padre-to-child and odd ones for the other direction.
In addition, your children continue with the padre loop whereas they should exit that loop immediately so their value of
iis correct. You do have the loop exit based onpadrebut this happens afterihas changed. You can either break where you setpadreto false or simplyi--in theif(!padre)bit to restoreito the correct value for this child. I’ve done the latter.The following code (with markers showing what changed) works okay:
This generates the correct answer of 2046, since
20 + 21 + ... 210 = 211 - 1and, since you’re leaving out the two-to-the-zero term (equal to 1):21 + 22 + ... 210 is 211 - 2 (211 = 2048).