1

複数のパイプを実装する ac プログラムを作成していますが、dup2 が子プロセスを早期に終了させるため問題が発生しています。これが私のコードです:

// so you have i number of commands
fcommand = i;
for(i = 0; i < (fcommand - 1); ++i){
    if( pipe(fd + i*2) < 0 ){
        printf("Error!: cannot create file descripters\n");
        exit(5);
    }
}
++i;
printf("%d\n", i);
j = -1;
cdc = 0;
while(i >= 1){
    pid = fork();//creating a child
    if(pid == 0){//i.e. if its a child
        if(i != fcommand){//i.e. if there is a previous command
            if( dup2(fd[(cdc-1)*2], 0) < 0){// 0 -----> stdin
                printf("Error!: cannot duplicate file descriptors\n");
                exit(6);
            }
        }
        if(i != 1){
            if(dup2(fd[cdc*2+1], 1) < 0 ){// this is where the problem occurs
                printf("Error!: cannot duplicate file descriptors\n");
                exit(7);
            }
        }
        k = 0;
        while(k < ((2 * (fcommand - 1))))
            close(fd[k++]);
        ++j;
        if(execvp(in[j].enter[0], in[j].enter) < 0){
            printf("%s: command not found!\n", in[j].enter[0]);
            exit(1);
        }                               
    }
    else{ 
        if(pid < 0){//if error
            printf("Error!: cannot create a new process\n");
            exit(8);
        }
        if(pid > 0){//if a parent
            while(wait(&status) > 0);
            --i;
            cdc++;
        }
    }
}

コマンドを実行すると、最初のコマンドの結果が出力され、パイプ内の残りのコマンドを実行せずにプログラムが終了します。

dup2子プロセスが途中で終了 する理由についてのアイデアはありますか?

4

0 に答える 0