了解管道 [英] Understanding pipes

查看:59
本文介绍了了解管道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想打印某些顺序的N个元素,例如1,2,4,8 ...,而我试图使用N个子进程和N-1个管道来实现.因此,当进程"i"计算"a [i]"时,它将该值传递给进程i + 1,这样他就可以计算a [i + 1],依此类推...

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...

我写了这个:

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);        
    }   
}

对我来说似乎正确,但是我得到的N = 5的序列是2 1 2 48.Somebody.help.me.

it seems right to me,but the sequence I get for N=5 is 2 1 2 4 8. Somebody.help.me.

推荐答案

最后一个子进程( i == N-1 )读取 cev [N-1] [0] 超出了 cev 的末尾.类似地,进程 N-2 写入结束后的 cev [N-1] [1] .您需要将所有管道索引偏移-1:

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));

这篇关于了解管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆