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

标签 c shell system systems-programming

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

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

最佳答案

您必须首先对您的输入命令进行分词。

Token 是一个或多个确实有意义的符号的集合。

例如& , | , > , >> , <是代币。

看看here了解如何开始编写词法分析器(没那么复杂)。

也许编译器构建的一些基础知识也会有所帮助。

关于c - 使用组合管道和重定向编写 C Shell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15940418/

相关文章:

linux - 不能添加超过 2 个变量

wpf - 如何避免/阻止系统绘制/重绘/刷新/绘制 WPF 窗口

用于访问 Windows 10 上的 Android 文件系统的 python 脚本

c - 使用递归创建哈希码函数

c - 如何检查 CLI 程序是否正在等待来自标准输入的输入?

c - 为子函数中的结构指针分配空间

c++ - 获取 int 中不除以 10 的位数

linux - 如何提取字符串开头的一部分?

bash - 列出高于特定数字的数字文件

c - 系统调用 open() 似乎在创建文件时随机设置文件权限