在自制shell C++中实现多个管道
我只是把执行过程的代码放在这里 存在一个包含成员char*command_list[MAXCOMMANDS][MAXARGUMENTS]的结构 此成员中每行的第一个位置包含命令,该行中的其余项为参数 我已经做了一个执行程序,它在给出ls | wc的输入时给出** DUP2此处:错误的文件描述符 下面的结构在自制shell C++中实现多个管道,c++,linux,shell,pipe,C++,Linux,Shell,Pipe,我只是把执行过程的代码放在这里 存在一个包含成员char*command_list[MAXCOMMANDS][MAXARGUMENTS]的结构 此成员中每行的第一个位置包含命令,该行中的其余项为参数 我已经做了一个执行程序,它在给出ls | wc的输入时给出** DUP2此处:错误的文件描述符 下面的结构 struct command { ifstream input; ofstream output; int num_commands=-1; int
struct command
{
ifstream input;
ofstream output;
int num_commands=-1;
int num_args[MAXCOMMANDS]={0};
char* command_list[MAXCOMMANDS][MAXARGS]; //command and their arguments storage
vector<string> pr_operator; //Pipe or redirection operators storage
bool background_task;
bool append;
};
执行下面的函数
int execute()
{
pid_t pid,wpid;
int status;
int num_pipes=count_pipes();
int pfds[2*num_pipes];
for(int i=0;i<num_pipes;i++)
{
if(pipe(pfds+2*i)<0)
{
perror("Cannot Pipe");
exit(1);
}
}
for(int i=0,j=0;i<=s.num_commands;i++,j+=2)
{
pid=fork();
if(pid==0)
{
if(i>0) //if not first command
{
if(dup2(pfds[j-2],0)<0)
{perror("DUP2 HERE");exit(1);}
close(pfds[j-2]);
close(pfds[j-1]);
}
if(i<s.num_commands) // if not last command
{
if(dup2(pfds[j+1],1)<0)
{perror("DUP2");exit(1);}
close(pfds[j+1]);
close(pfds[j]);
}
if(execvp(s.command_list[i][0],s.command_list[i])==-1)
{
perror("My Shell");
exit(1);
}
}
else if(pid<0)
{
perror("My Shell");
exit(1);
}
else
{
for(int k=0;k<2*num_pipes;k++)
close(pfds[k]);
for(int k=0;k<num_pipes+1;k++)
wait(&status);
}
}
return 1;
}
呃,让pfds成为一个二维数组,而不是一个长数组。您是否尝试过使用调试器运行它,以便在错误发生时检查pfds[j-2]的值?调试器在系统调用中没有帮助跟踪将有助于系统调用。另外,is.num_命令初始化为-1,因此当它为0时,命令数为1