使用组合管道和重定向编写C Shell

时间:2013-04-11 03:48:40

标签: c shell system systems-programming

我正在尝试在C中实现一个迷你shell,它将接受<,>,>>,|,&的任何组合。我有它到读取命令和执行文件重定向等的地方,但是,我似乎无法通过谷歌找到一个很好的教程,如何编程它接受上述命令的任何组合。我到目前为止的代码如下(我删除了我尝试过的组合东西bc我不知道如何做它并且它是一团糟)(一些非标准函数来自库我我正在使用。):

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;
}

1 个答案:

答案 0 :(得分:0)

您必须首先对输入命令进行标记。

令牌是一个或多个具有意义的标志的集合。

例如&|>>><是令牌。

看看here,了解如何开始编写词法分析器(它并不复杂)。

也许一些编译器构建的基础知识也可以提供帮助。