我正在尝试在 C 中实现一个迷你 shell,它将接受 <、>、>>、|、& 的任何组合。我把它放在它读取命令和执行文件重定向等的地方,但是,我似乎无法通过谷歌找到一个关于如何对其进行编程以接受上述命令的任何组合的好的教程。到目前为止我的代码如下(我删除了我尝试过的组合内容,因为我不知道该怎么做,而且一团糟)(一些非标准函数来自我正在使用的库。 ):
int main(int argc, char **argv)
{
int i,j,frv,status,x,fd1;
IS is;
is = new_inputstruct(NULL);
/* read each line of input */
while (get_line(is) >= 0)
{
if (is->NF != 0)
{
/*fork off a new process to execute the command specified */
frv = fork();
/* if this is the child process, execute the desired command */
if (frv == 0)
{
if (strcmp(is->fields[is->NF-1],"&") == 0) is->fields[is->NF-1] = NULL;
while (is->fields[frv] != NULL)
{
/* if we see <, make the next file standard input */
if (strcmp(is->fields[frv],"<") == 0)
{
is->fields[frv] = NULL;
fd1 = open(is->fields[frv+1], O_RDONLY);
dup2(fd1, 0);
close(fd1);
}
/* if we see >, make the next file standard output and create/truncate it if needed */
else if (strcmp(is->fields[frv],">") == 0)
{
is->fields[frv] = NULL;
fd1 = open(is->fields[frv+1],O_TRUNC | O_WRONLY | O_CREAT, 0666);
dup2(fd1, 1);
close(fd1);
}
/* if we see >>, make the next file standard output and create/append it if needed */
else if (strcmp(is->fields[frv],">>") == 0)
{
is->fields[frv] = NULL;
fd1 = open(is->fields[frv+1], O_WRONLY | O_APPEND | O_CREAT, 0666);
dup2(fd1, 1);
close(fd1);
}
frv++;
}
/* execute the command */
status = execvp(is->fields[0], is->fields);
if (status == -1)
{
perror(is->fields[0]);
exit(1);
}
}
/* if this is parent process, check if need to wait or not */
else
{
if (strcmp(is->fields[is->NF-1],"&") != 0) while(wait(&status) != frv);
}
/* clean up the values */
for(j = 0; j < is->NF; j++) is->fields[j] = NULL;
}
}
return 0;
}