我正在尝试在C中实现一个shell。 参考https://stackoverflow.com/questions/12128185/implementing-multiple-pipes-for-linux-unix-shell, 我设计了我的代码:
void piped(char *** tokens_basic, int nPipes)
{
int pipefds[2 * nPipes];
for(int i=0; i<nPipes; i++)
{
if(pipe(pipefds + i*2) < 0)
{
perror("Error in piping");
exit(EXIT_FAILURE);
}
}
pid_t pid;
int status;
int i=0, j=0, k;
while(tokens_basic[i] != NULL)
{
pid = fork();
if(pid == 0)
{
if(tokens_basic[i+1] != NULL)
{
if(dup2(pipefds[j + 1], 1) < 0)
{
perror("dup2 in j+1");
exit(EXIT_FAILURE);
}
}
if(j != 0)
{
if(dup2(pipefds[j-2], 0) < 0)
{
perror("dup2");
exit(EXIT_FAILURE);
}
}
for(k = 0; k < 2*nPipes; k++)
{
close(pipefds[k]);
}
if(execvp(tokens_basic[i][0], tokens_basic[i]) < 0)
{
perror("Error in child execvp");
exit(EXIT_FAILURE);
}
}
else if(pid < 0)
{
perror("Error in pipe fork.");
exit(EXIT_FAILURE);
}
else
{
i++;
j += 2;
}
}
for(i = 0; i < 2 * nPipes; i++)
{
close(pipefds[i]);
}
for(i = 0; i < nPipes + 1; i++)
wait(&status);
}
在此我得到以下输出:
dup2 in j+1: Bad file descriptor
dup2: Bad file descriptor
dup2: Bad file descriptor
dup2 in j+1: Bad file descriptor
dup2: Bad file descriptor
dup2 in j+1: Bad file descriptor
dup2 in j+1: Bad file descriptor
dup2: Bad file descriptor
Error in child execvp: No such file or directory
Error in child execvp: No such file or directory
Error in child execvp: No such file or directory
Error in child execvp: No such file or directory