From 2b2827eb1875bc2e3cfc309e8590c5c059e48e57 Mon Sep 17 00:00:00 2001 From: "S.J.R. van Schaik" Date: Tue, 18 Jul 2017 12:59:26 +0200 Subject: [PATCH] shell: simplify prompt() --- source/shell/cmd.c | 30 ++++++++---------------------- 1 file changed, 8 insertions(+), 22 deletions(-) diff --git a/source/shell/cmd.c b/source/shell/cmd.c index 36e11c8..1f59d98 100644 --- a/source/shell/cmd.c +++ b/source/shell/cmd.c @@ -5,6 +5,7 @@ #include static int should_exit = 0; +static char buf[128]; static void do_exit(const char *s); struct cmd main_cmds[] = { @@ -25,35 +26,21 @@ static void do_exit(const char *s) static char *prompt(const char *prefix) { - char *alloc, *line; - size_t nbytes = 0, nalloc_bytes = 16; - char c; + size_t len; printf(prefix); - if (!(line = malloc(nalloc_bytes))) + if (!fgets(buf, 128, stdin)) return NULL; - while ((c = getchar()) && c != '\n') { - if (nbytes + 1 >= nalloc_bytes) { - nalloc_bytes *= 2; + len = strlen(buf); - if (!(alloc = realloc(line, nalloc_bytes))) - goto err_free_line; + if (len > 0 && buf[len - 1] == '\n') + buf[len - 1] = '\0'; - line = alloc; - } - - line[nbytes++] = c; - } - - line[nbytes] = '\0'; - - return line; + putchar('\n'); -err_free_line: - free(line); - return NULL; + return buf; } void cmd_exec(struct cmd *cmds, const char *line) @@ -88,6 +75,5 @@ void cmd_loop(const char *show) while (!should_exit) { line = prompt(show); cmd_exec(main_cmds, line); - free(line); } }