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

DaW*_*ood -1 c linux debian

以下代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

结果在提示符(daw.0>)中反复打印出来(单词数量 - 1次).例如,II键入"你好大家好,你好吗?",输出如下:

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

daw.0>
daw.0>
daw.0>
daw.0>
daw.0>
daw.0>
Run Code Online (Sandbox Code Playgroud)

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

P.P*_*.P. 5

scanf()%s在所述第一空白停止扫描.这解释了你观察到的行为.

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