0

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.

4

1 回答 1

2

The last child process (i == N - 1) reads cev[N - 1][0] which is past the end of cev. Similarly process N - 2 writes to cev[N - 1][1] which is also past the end. You need to offset all of the pipe indices by -1:

if(i>0) {
  read(cev[i-1][READ],&a,sizeof(int));
  a = f(a);  // calculate next element
}
printf("%d     ",a); fflush(stdout);                        
if(i!=N-1) write(cev[i][WRITE],&a,sizeof(int));
于 2013-08-14T22:12:31.987 回答