C Debian Linux 中简单 shell 的意外行为

Unexpected behavior from simple shell in C Debian Linux

以下代码:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#define MAX_LINE 80 /* Max command length */

int main(void)
{
   char fullCmd[MAX_LINE-1];
   const char *EXIT_CMD = "exit"; /* command to exit shell */
   int should_run = 1; /* flag to determine when to exit*/

   while (should_run)
   {
      printf("daw.0>");
      fflush(stdout);
      scanf("%s", fullCmd);

      if (strcmp(fullCmd, EXIT_CMD) == 0)
      {
         should_run = 0;
      }
   }
   return 0;
}

结果提示(daw.0>)重复打印出来(字数- 1次)。比如我输入"Hello there everyone, how are you?",看到如下输出:

daw.0>Hello there everyone, how are you?

daw.0>
daw.0>
daw.0>
daw.0>
daw.0>
daw.0>

我不明白为什么。我还有很多工作要做才能为作业创建 shell,但我什至无法获得最简单的变体来可靠地工作。我在 Virtual Box 中使用 Linux 的 Debian 发行版。

scanf()%s 在第一个白色 space 处停止扫描。这解释了您观察到的行为。

您可能想使用的是 fgets()。请注意,如果缓冲区中有足够的 space,fgets() 也会读取换行符。如果这是你不想要的,那么你必须删除尾随的换行符(如果有的话)。