0

我是 linux 的初学者,但是我已经设法做了自己的 shell。是时候在其中添加管道了。(就是这样,作业说)。谁能向我解释一下如何做到这一点?我知道理论上,它应该这样工作。

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

这是一个shell命令的例子

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

我已经向您展示了如何在两个进程的情况下执行此操作,但您可以了解总体思路并将其调整到其他情况。

希望有帮助!

于 2012-11-10T22:13:08.693 回答