1

我正在努力创建自己的外壳。

我为用户输入创建了一个词法分析器和一个解析器(它创建了一个二叉树)。所以对于这样的命令:cat main.c | ls | 厕所

我得到了这棵树:

           "|"
           / \
          /   \
         /     \
 "cat main.c"   "|"
                / \
               /   \
             "ls"  "wc"

所以我的树遍历函数(按顺序)是这样的:

inorder(root)
{
   inorder(root->left);
   //exec cmd and do redirection

   inorder(root->right);
}

我的问题是当我在节点“ls”或“wc”上时,我不知道如何检查命令前后是否有管道。

任何想法 ?

4

1 回答 1

1

在您的解析树中,管道是节点,命令是叶子。管道必须同时具有左右分支。当您从管道向左走时,您现在所在的管道是您要执行的命令的输出管道。当您向右走时,您所在的管道是目标命令的输入管道。

因此,将输入和输出管道作为参数传递。他们指出NULL该命令是否没有重定向或指向其中一个|节点。

inorder(root, in, out)
{
    if (root is cmd) {
        execute(root, in, out);
    } else {
        // root is pipe
        inorder(root->left, in, root);
        redirect(in, out);
        inorder(root->right, root, out);
    }
}

从树的根部开始inorder(root, NULL, NULL)

于 2014-01-25T19:27:10.353 回答