Unexpected behavior from simple shell in C Debian Linux -
the following code:
#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 exit shell */ int should_run = 1; /* flag determine when exit*/ while (should_run) { printf("daw.0>"); fflush(stdout); scanf("%s", fullcmd); if (strcmp(fullcmd, exit_cmd) == 0) { should_run = 0; } } return 0; }
results in prompt (daw.0>) printing out repeatedly (the number of words - 1 times). example, i type in "hello there everyone, how you?", following output seen:
daw.0>hello there everyone, how you? daw.0> daw.0> daw.0> daw.0> daw.0> daw.0>
i don't understand why. have lot more need create shell assignment, can't simplest variation work reliably. using debian distribution of linux in virtual box.
scanf()
%s
stops scanning @ first whitespace. explains behaviour observe.
what wanted use fgets()
. aware fgets()
reads in newline if there's sufficient space available in buffer. if don't want have remove trailing newline (if any).
Comments
Post a Comment