I want to print N elements of some sequence, like 1,2,4,8... and I'm trying to do that with N child processes and N-1 pipes. So, when process "i" calculates "a[i]" it passes that value to process i+1 so he can calculate a[i+1] and so on...
I've written this:
int main(){
int a = 1;
int i,j;
int cev[N-1][2];
for(i=0; i<N-1; i++) pipe(cev[i]);
for(i=0; i<N; i++){
if(fork() == 0){ // child
if(i>0){
read(cev[i][READ],&a,sizeof(int));
a = f(a); // calculate next element
}
printf("%d ",a); fflush(stdout);
if(i!=N-1) write(cev[i+1][WRITE],&a,sizeof(int));
// closing copies of pipes
for(j=0; j<N-1; j++){
close(cev[j][READ]);
close(cev[j][WRITE]);
}
exit(0);
}
}
it seems right to me,but the sequence I get for N=5 is 2 1 2 4 8. Somebody.help.me.