【问题标题】:Writing a command line shell with C; trying to use ncurses/C for the first time用 C 编写命令行 shell;第一次尝试使用 ncurses/C
【发布时间】:2011-04-04 23:05:34
【问题描述】:

我正在做一个课堂项目,我必须编写一个具有以下要求的命令行 shell:

  • shell 必须能够读取缓冲输入
  • 缓冲区应为 64 个字符
  • 应处理错误情况
    • 超出缓冲区大小
    • 中断(当信号到达时) - 请参阅 read() 的手册页
    • 输入无效(无法解析的字符、空行等)
    • 可能遇到的任何其他错误。
  • Shell 必须具有至少 20 个项目的历史记录,并且历史记录不能是静态大小。当历史缓冲区已满时,将删除最旧的项目并添加最新的项目。
  • 程序应该能够在前台或后台运行。 (使用 &)
  • Ctrl-D 将退出 shell
  • Ctrl-C 将打印完整的历史记录
  • 命令“历史”也将打印完整的历史。最新项目将位于列表底部。
  • 所有其他信号都将被捕获并在 shell 中显示给用户
  • 程序将使用 read() 命令读取输入,除非支持箭头键

我选择为历史循环实现箭头键,所以我使用 ncurses 进行输入,而不是 read()。我认为我使用 strtok() 来解析输入并使用 fork() 和 execvp() 来运行进程,但我并没有正确地实现 ncurses。到目前为止,我所做的只是初始化一个新屏幕,显示提示,然后在任何按键时出现段错误。不好。

我认为问题一定出在我的设计中。我并没有很好地围绕 ncurses 进行思考。我应该为这个项目使用什么样的数据结构?我应该如何处理 ncurses 设置、拆卸以及介于两者之间的所有内容?窗口和屏幕有什么关系,我应该使用一个全局可访问的窗口/屏幕吗?此外,我一直在尝试使用 char* 作为输入缓冲区,使用 char** 作为命令历史记录,但我没有 C 语言经验,所以尽管阅读了 malloc、calloc 和 realloc,我还是不确定将命令存储在缓冲区和历史记录中的最佳方式。管理这些 char 数组有什么技巧吗?

tl;dr:如何正确使用 ncurses 制作命令行 shell,以及如何使用 C 处理命令内存管理?

我意识到这是一个非常重要的问题。 :(

编辑:我已经看过 http://www.gnu.org/software/libc/manual/html_node/Implementing-a-Shell.html 和 http://www.linuxinfor.com/english/NCURSES-Programming/ 但 ncurses 文档实际上有太多开销。我只是想利用它识别方向键的能力。

【问题讨论】:

    标签: c solaris process ncurses


    【解决方案1】:

    下面是一些示例代码:

    1. 执行动态内存分配。

    2. 以非阻塞模式从控制台读取。

    3. 使用 VT100 代码将帧缓冲区打印到控制台。

    它使用 GCC 在 Linux 上编译,没有警告或错误。它远非没有错误,但它应该给你一些关于什么是可能的想法。编译并运行它,按 [up] 和 [down] 将打印消息,输入字符并按 [enter] 将“执行”命令。

    #include <poll.h>
    #include <signal.h>
    #include <stdio.h>
    #include <termios.h>
    #include <unistd.h>
    #include <stdlib.h>
    #include <string.h>
    #include <time.h>
    
    /** VT100 command to clear the screen. Use puts(VT100_CLEAR_SCREEN) to clear
     *  the screen. */
    #define VT100_CLEAR_SCREEN "\033[2J"
    
    /** VT100 command to reset the cursor to the top left hand corner of the
     *  screen. */
    #define VT100_CURSOR_TO_ORIGIN "\033[H"
    
    struct frame_s
    {
        int x;
        int y;
        char *data;
    };
    
    static int draw_frame(struct frame_s *frame)
    {
        int row;
        char *data;
        int attrib;
    
        puts(VT100_CLEAR_SCREEN);
        puts(VT100_CURSOR_TO_ORIGIN);
    
        for (row = 0, data = frame->data; row  < frame->y; row++, data += frame->x)
        {
            /*  0 for normal, 1 for bold, 7 for reverse. */
            attrib = 0;
    
            /*  The VT100 commands to move the cursor, set the attribute, and the
             *  actual frame line. */
            fprintf(stdout, "\033[%d;%dH\033[0m\033[%dm%.*s", row + 1, 0, attrib, frame->x, data);
            fflush(stdout);
        }
    
        return (0);
    }
    
    int main(void)
    {
        const struct timespec timeout = { .tv_sec = 1, .tv_nsec = 0 };
        struct frame_s frame;
        struct termios tty_old;
        struct termios tty_new;
        unsigned char line[128];
        unsigned int count = 0;
        int ret;
        struct pollfd fds[1];
        sigset_t sigmask;
        struct tm *tp;
        time_t current_time;
    
        /*  Set up a little frame. */
        frame.x = 80;
        frame.y = 5;
        frame.data = malloc(frame.x * frame.y);
    
        if (frame.data == NULL)
        {
            fprintf(stderr, "No memory\n");
            exit (1);
        }
    
        memset(frame.data, ' ', frame.x * frame.y);
    
        /*  Get the terminal state. */
        tcgetattr(STDIN_FILENO, &tty_old);
        tty_new = tty_old;
    
        /*  Turn off "cooked" mode (line buffering) and set minimum characters
         *  to zero (i.e. non-blocking). */
        tty_new.c_lflag &= ~ICANON;
        tty_new.c_cc[VMIN] = 0;
    
        /*  Set the terminal attributes. */
        tcsetattr(STDIN_FILENO, TCSANOW, &tty_new);
    
        /*  Un-mask all signals while in ppoll() so any signal will cause
         *  ppoll() to return prematurely. */
        sigemptyset(&sigmask);
    
        fds[0].events = POLLIN;
        fds[0].fd = STDIN_FILENO;
    
        /*  Loop forever waiting for key presses. Update the output on every key
         *  press and every 1.0s (when ppoll() times out). */
        do
        {
            fds[0].revents = 0;
            ret = ppoll(fds, sizeof(fds) / sizeof(struct pollfd), &timeout, &sigmask);
    
            if (fds[0].revents & POLLIN)
            {
                ret = read(STDIN_FILENO, &line[count], sizeof(line) - count);
    
                if (ret > 0)
                {
                    line[count + ret] = '\0';
    
                    if (strcmp(&line[count], "\033[A") == 0)
                    {
                        snprintf(frame.data, frame.x, "up");
                        count = 0;
                    }
                    else if (strcmp(&line[count], "\033[B") == 0)
                    {
                        snprintf(frame.data, frame.x, "down");
                        count = 0;
                    }
                    else if (line[count] == 127) // backspace
                    {
                        if (count != 0) { count -= ret;}
                    }
                    else if (line[count] == '\n')
                    {
                        snprintf(frame.data, frame.x, "entered: %s", line);
                        count = 0;
                    }
                    else
                    {
                        count += ret;
                    }
                }
            }
    
            /*  Print the current time to the output buffer. */
            current_time = time(NULL);
            tp = localtime(&current_time);
            strftime(&frame.data[1 * frame.x], frame.x, "%Y/%m/%d %H:%M:%S", tp);
    
            /*  Print the command line. */
            line[count] = '\0';
            snprintf(&frame.data[(frame.y - 1) * frame.x], frame.x, "$ %s", line);
    
            draw_frame(&frame);
        }
        while (1);
    
        /*  Restore terminal and free resources. */
        tcsetattr(STDIN_FILENO, TCSANOW, &tty_old);
        free(frame.data);
    
        return (0);
    }
    

    【讨论】:

    • 我阅读了代码,然后尝试实现它,但 ppoll 是一个未定义的符号。我正在尝试在 Solaris 上使用 GCC 进行编译(这是一台大学机器)。
    • 如果有帮助,我不能人工 ppoll 但我可以在机器上人工投票。
    • 好吧,我做了一些功课,poll() conforms to POSIX.1-2001. ppoll() is Linux specific...你能不能把代码改成不使用 ppoll()?
    • 没关系!获得帮助here。顺便说一句,你有一个有趣的错误是提示可以退格:)
    • 毫无疑问是该示例中的许多错误之一;-) 祝您设计顺利,我在另一个问题中看到您现在已经在 Solaris 中运行了。
    【解决方案2】:

    如果您的输入缓冲区定义为 64 个字符,那么我建议使用 char 数组而不是 char*。像char input_buffer[65]; 这样的东西应该可以满足您的目的(为结尾的'\0' 添加一个额外的字符)。

    就命令历史而言,您可以为此使用二维数组。 char command_history[20][65]; 之类的东西应该可以让你存储 20 个旧命令,每个命令 64 个字符。

    静态分配这些缓冲区应该会让事情变得更容易一些,因为您不必担心malloc 和朋友们。

    如果不看你的代码,很难给你太多具体的建议。我有一种感觉,您正在犯与第一次学习 C 的人常见的相同类型的错误。您能否发布您的代码中给您带来问题的部分,以便我们可以更多地了解您在做什么?

    发布提供的代码后更新:

    我看到的一个问题是函数takeInput 没有返回语句。当您在 main 函数中使用 input = takeInput(); 时,input 的值并未设置为您认为的值。它可能不是一个有效的指针,这会导致您的 input[j] 行出现段错误。

    您对cmdHistory 的使用也需要重新审视。你用cmdHistory = (char**)calloc(21,sizeof(int)); 分配它,它给你足够的空间来存储21 个整数。在函数printHistory 中,您将cmdHistory 的元素传递给printw,就好像它们是字符串一样(它们只是整数)。这绝对不是你想做的事。相反,cmdHistory 的分配逻辑需要看起来更像您的取消分配逻辑(向后除外)。分配char** 的数组,然后遍历数组,将每个指针分配给新分配的缓冲区。就像您对数组中的每个元素都有一个 free 语句加上整个数组的 free 一样,您应该对每个元素有一个 malloc 加上一个 malloc 对整个数组。

    即使您不能使用静态分配的堆栈,也请尝试使用静态分配的堆栈来编写程序。这将使您可以解决关键检测逻辑等问题,而不必担心程序的动态内存部分。一旦其余部分正常工作,请返回并换出静态内存以进行动态内存分配。这样,您一次只需要调试一点点。

    【讨论】:

    • 我会发布我的代码,但它非常糟糕。我不是编程新手,只是 C,我意识到筛选不良源代码是多么可怕,但感谢您的帮助!我的问题是,我不允许静态地声明我的历史……教授说这样做会受到惩罚。我怎样才能动态地做到这一点?
    • 破码没问题。如果有效,则无需发布 :-) 您也可以使用 malloc 来分配数组。例如,malloc(65 * sizeof(char)) 将分配足够的空间来存储 65 个字符。
    • 好的,但是calloc 呢?就像,如果我要在缓冲区的第一个开放空间插入,如果我使用malloc,我要检查取消引用的指针值是否相等?对于calloc,如果我是正确的,它应该是0,所以如果我是正确的,我可以做一个while (*buff != 0) ++buff; 来遍历缓冲区。
    • 在malloc 缓冲区之后,您可以使用memset 将其归零。我不建议在那里使用while (*buff != 0),因为没有什么可以阻止你跑出缓冲区的末尾(破坏内存或段错误)。我建议将malloc 返回的值视为一个数组,创建一个变量int idx; 用作数组的索引,并使用while (buffer[i] != 0 &amp;&amp; i &lt; 64) 作为循环控制参数。您还可以创建一个char* 以指向缓冲区中的下一个开放空间,这样您就不必使用循环搜索它。
    • 好吧,好吧,这里是代码:header ... source
    【解决方案3】:

    您看过 Readline 库吗?它非常适合在您的项目中使用。

    http://cnswww.cns.cwru.edu/php/chet/readline/rltop.html

    【讨论】:

    • 我在那个网站上读了一会儿,它确实继续关于键盘快捷键...我不想实现这些快捷键中的任何一个。另外,这个库是否可以让我检查每个键盘输入,以便我可以检测到箭头键?我不想获取一行文字,我想单独获取字符。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-17
    • 2014-04-24
    • 2021-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多