我知道已经有人问过类似的问题,但没有一个答复对我有帮助。我正在尝试实现一个微型 Linux shell 并被困在多个管道上。带有单个管道(例如ls | wc
)的命令可以工作,但是如果我添加第二个管道,控制台上不会显示任何内容。这是我的代码。
void ExecuteCommand(NODE *cHead,NODE *oHead)
{
int fd[10][2]; // file descriptors' array
int nfdCnt = 0 ; // file descriptors counter
string strCmd; // command
string strOp = ""; // operator
int nOpCnt = 0 ; // operator count
while(1)
{
if (cHead != NULL) // cHead is head pointer to the linked list of commands.
{
strCmd = GetCmdOROperator(&cHead); // get command
}
if (oHead == NULL) // oHead is head pointer to the linked list of operators.
{
strOp = "";
}
else
{
strOp = GetCmdOROperator(&oHead); // get operator
}
if (strOp.empty()) // no operator exists. single or last command in the chain.
{
// Fork the child process
pid_t child_id = fork();
if(child_id == 0)
{
// Execute the command
if (nOpCnt) // if we previously encountered any operator
{
close(fd[nfdCnt-1][FD_WRITE]);
dup2(fd[nfdCnt-1][FD_READ], FD_READ); // read from pipe updated by previous command
}
// call execvp()
exit(-1);
}
else
{
for (int i = 0 ; i < nfdCnt; i++)
{
close(fd[nfdCnt][0]);
close(fd[nfdCnt][1]);
}
wait(NULL);
break;
}
}
if (strOp == "|")
{
nOpCnt++ ;
if (pipe (fd[nfdCnt]) < 0)
{
printf("\npipe error");
return ;
}
pid_t child_id = fork();
if (child_id == 0)
{
close(fd[nfdCnt][FD_READ]); // we dont need this
dup2(fd[nfdCnt][FD_WRITE], FD_WRITE);
if(nOpCnt > 1) // if we have already encountered a pipe before
{
dup2(fd[nfdCnt-1][FD_READ],FD_READ);
close(fd[nfdCnt-1][FD_WRITE]);
}
// call execvp()
exit (-1);
}
else
{
nfdCnt++;
}
}
}
}