0

私はLinuxの初心者ですが、自分でシェルを作成することができました。そこにパイプラインを追加する時が来ました。(それは、宿題が言うことです)。誰かが私にそれを行う方法をもう少し説明できますか?理論的には、そのように機能するはずです。

unsigned char* child_results; //buffer to save results from child processes

for (int i = 0; i < 2; i++) {
    pid = fork();

    if (pid == 0) {
        //if it's the first process to launch, close the read end of the pipe
        //otherwise read what the parent writes to the pipe and then close the 
        //read end of the pipe

        //call execvp()
    }
    else {
        //if you've launched the first process, close the write end of the pipe
        //otherwise write the contents of child_result to the child process
        //and then close the write end of the pipe

        //read from the child's pipe what it processed

        //save the results in the child_results buffer

        wait(NULL); //wait for the child to finish
    }
}

しかし、私はそれを動作させることができません。私はその日を一日中やっていますが、それでも何もしていません。私はその考えを理解していますが、それを機能させることができません。some1は私を助けることができますか?これが私のパイプライン部分のコードです:

for (int i = 0; i <= pipeline_count; i++) { 
    int pdesc[2]; 
    // creating pipe
    pipe(pdesc);
    int b = fork();
    // child
    if (b == 0) {
        // 1st pipeline
        if (i == 0) {       
            //<?>               
        }

        // last pipeline
        if (i == pipeline_count) {                              
            //<?>
        }

        // inside pipeline
        if (i > 0 && i < pipeline_count)  {
            //<?>
        } 
        execvp(array[0], array);
    }
    else { 
        // parent
        //<?>
        wait(NULL);         
    }
}       

これがシェルコマンドの例です

ls -al | tr a-z A-Z

ありがとう

4

1 に答える 1

2

子の入力ストリームを閉じて、dupそのチャネルのパイプと複製する必要があります。親はパイプの反対側でも同じことをします。このようなもの:

b = fork();
if (b == 0) {
  /* Close stdin, and duplicate the input side of the pipe over stdin */
  dup2(0, pdesc[0]);
  execlp(...);
}
else {
  /* Close stdout, and duplicate the output side of the pipe over stdout */
  dup2(1, pdesc[1]);
  execlp(...);
}
...

2つのプロセスの場合にそれを行う方法を示しましたが、一般的なアイデアを取得して、他の状況に適応させることができます。

お役に立てば幸いです。

于 2012-11-10T22:13:08.693 に答える