我是 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
谢谢