【问题标题】:How to reissue shell prompt if only user input is enter?如果仅输入用户输入,如何重新发出 shell 提示?
【发布时间】:2013-12-12 23:52:00
【问题描述】:

我正在尝试制作自己的简单命令行解释器 (shell),如果唯一的用户输入是空格,我希望提示符重复。本质上,如果用户按下返回,我希望提示重复并等待下一个输入。我正在使用 fgets 获取输入,并将其存储在 char *commandBuffer 中,以便通过 parse() 方法进行解析。我原本想检查 argv(argc = 0) 中是否有参数,但这只会导致光标移动到新行而不会再次打印提示。例如,如果我在提示符处输入“\n\n\ncd”,cd 仍然有效。我想尝试解决的另一个问题是,为了将在提示符下键入的任何内容发送到 shell,用户必须按两次 enter。到目前为止,这是我的代码:

    for (;;) {
        printf("p2: ");
        fflush(stdout);


        /*---------FGETS PROMPT----------*/
        fgets(commandLine, STORAGE, stdin);
        ln = strlen(commandLine)-1;
        /* Removes trailing newline */
        if(commandLine[ln] == '\n')
            commandLine[ln] = '\0';
        /* ATTEMPT to repeat the prompt if only user input at prompt is enter*/
        if(commandLine[0] == '\0')
            continue;
 ....More shell code....

【问题讨论】:

  • 我之前也尝试过实现自己的控制台。你可能想试试libreadlinecnswww.cns.cwru.edu/php/chet/readline/rltop.html,它会让你的生活变得更简单。
  • 尝试在 if 块中检查 ln == 0 而不是检查 commandLine[0] == '\0'
  • @ronmrdechai:这是一个非常小的优化,不会导致任何功能变化。

标签: c shell fgets


【解决方案1】:

(由您调试): 我总是做这样的事情来生存命令中出现的任何空白。如果您在传入行的末尾收到 \r\n\0 或只是 \r\0,这也可以避免问题,这会导致您的代码片段问题。

字符 *cl;
for ( cl = commandLine; *cl && isspace(*cl); cp++ )
{
    如果 ( cl == 0 )
        休息; // 转义 for (cl = ...) 以返回到外部 for (;;)

    // 如果以相同的样式修剪尾随空白很重要:
    国际化; // 非空白文本的长度
  { // 限制 cl2 的范围
    字符 *cl2;
    for ( cl = strchr( cl, '\0' ); cl2 >= cl; cl2-- )
        if ( isspace(*cl2) )
             *cl2 = '\0';
  }
  ln = cl2 - cl + 1; // 我们可以快速计算

    ...在此处使用 cP 作为文本的开头执行其余循环
}

<b>*cl &amp;&amp;</b> isspace(*cl) 是在历史时期遇到中断的 isspace() 调用后留下的偏执狂。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-25
    • 1970-01-01
    • 1970-01-01
    • 2020-06-22
    • 2022-01-21
    • 1970-01-01
    相关资源
    最近更新 更多