【发布时间】:2015-10-10 05:56:20
【问题描述】:
以下代码:
#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 次)。例如,我输入“大家好,你好吗?”,会看到以下输出:
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 发行版。
【问题讨论】:
-
编译时包含所有警告和调试信息 (
gcc -Wall -Wextra -g)。使用调试器gdb。读一整行(见this...),然后再解析。 -
%s读取一个单词,而不是一行。 -
这里是题外话。我们不会为你做作业。 BTW,你真的应该研究一些现有shell的源代码......(它们都是免费软件)