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

C Debian Linux中简单shell的意外行为,c,linux,debian,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

以下代码:

#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;
}
我不明白为什么。要为任务创建shell,我还需要做很多工作,但我甚至不能让最简单的变体可靠地工作。我正在使用Linux的Debian虚拟机发行版。

scanf()
with
%s
在第一个空格处停止扫描。这就解释了你观察到的行为


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

使用所有警告和调试信息编译(
gcc-Wall-Wextra-g
)。使用调试器
gdb
。阅读整行(请参阅…),然后稍后对其进行分析。
%s
只读取一个单词,而不是一行。此处为Off-topice。我们不会为你做家庭作业。顺便说一句,你真的应该研究一些现有shell的源代码。。。(他们都是自由软件)我想我太慢了。但我不妨加上这个。在中间,它说<代码> s匹配一个非空白字符序列 @ ARC667谢谢!也添加了链接。我建议
getline
readline
,请参阅
fgets
(强制限制行的最大长度)只能在您没有
getline
时使用,这在所有POSIX系统上都存在。@BasileStrynkevich从来不知道
readline
。很酷的功能。“请注意,
fgets()
也会读取换行符”。是一些关于删除换行符以及删除STDIN中多余数据的额外信息,以防止提示出现太多次。
daw.0>Hello there everyone, how are you?

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