这是一个用C ++创建shell的赋值。
我输入ls | sort
它完美无缺。但是当我输入另一个命令(ls | sort | head
)时,它无法运行并显示此错误:
error: Resource temporarily unavailable
makefile:8: recipe for target 'test' failed
make: *** [test] Error 1
这是代码
void rePipe(pid_t pid[], vector<Command> cmds, int count)
{
if(count == cmds.size())
{
return;
}
pid[count] = fork();
if (pid[count] < 0)
{
perror( "error" );
exit(1);
}
else if (pid[count] == 0) //child
{
if(cmds[count].input)
{
int fin = open(cmds[count].inputfile, O_RDONLY, 0666);
dup2(fin, 0);
close(fin);
}
if(cmds[count].output)
{
int fout = open(cmds[count].outputfile, O_WRONLY|O_CREAT, 0666);
dup2(fout, 1);
close(fout);
}
if(count == (cmds.size() -1) )
{
close(cmds[count-1].pipeNum[1]);
dup2(cmds[count-1].pipeNum[0], 0);
}
else
{
close(cmds[count-1].pipeNum[1]);
dup2(cmds[count-1].pipeNum[0], 0);
dup2(cmds[count].pipeNum[1], 1);
close(cmds[count].pipeNum[1]);
}
execvp (cmds[count].cmd[0], cmds[count].cmd);
perror("Can't execute" );
exit(1);
}
else
{
if(count < (cmds.size() -1))
rePipe(pid, cmds, count++);
wait(NULL);
}
}
void execute(vector<Command> cmds)
{
int count = 0;
for(int i=0; i < cmds.size(); ++i)
pipe(cmds[i].pipeNum);
pid_t pid[cmds.size()];
pid[count] = fork();
if (pid[count] < 0)
{
perror( "error" );
exit(1);
}
else if (pid[count] == 0) //child
{
if(cmds[count].input)
{
int fin = open(cmds[count].inputfile, O_RDONLY, 0666);
dup2(fin, 0);
close(fin);
}
if(cmds[count].output)
{
int fout = open(cmds[count].outputfile, O_WRONLY|O_CREAT, 0666);
dup2(fout, 1);
close(fout);
}
if(cmds.size() > 1)
{
close(cmds[count].pipeNum[0]);
dup2(cmds[count].pipeNum[1], 1);
close(cmds[count].pipeNum[1]);
}
execvp (cmds[count].cmd[0], cmds[count].cmd);
perror("Can't execute" );
exit(1);
}
else //parent
{
if(cmds.size() > 1)
{
rePipe(pid, cmds, 1);
}
for(auto & cmd: cmds)
{
close(cmd.pipeNum[0]);
close(cmd.pipeNum[1]);
}
if ( waitpid( pid[cmds.size() - 1], 0, 0 ) < 0 )
{
perror( "Internal error: cannot wait for child." );
exit(1);
}
}
}