shell: simplify prompt()
This commit is contained in:
parent
e4d0dc3cb3
commit
2b2827eb18
1 changed files with 8 additions and 22 deletions
|
@ -5,6 +5,7 @@
|
||||||
#include <shell.h>
|
#include <shell.h>
|
||||||
|
|
||||||
static int should_exit = 0;
|
static int should_exit = 0;
|
||||||
|
static char buf[128];
|
||||||
static void do_exit(const char *s);
|
static void do_exit(const char *s);
|
||||||
|
|
||||||
struct cmd main_cmds[] = {
|
struct cmd main_cmds[] = {
|
||||||
|
@ -25,35 +26,21 @@ static void do_exit(const char *s)
|
||||||
|
|
||||||
static char *prompt(const char *prefix)
|
static char *prompt(const char *prefix)
|
||||||
{
|
{
|
||||||
char *alloc, *line;
|
size_t len;
|
||||||
size_t nbytes = 0, nalloc_bytes = 16;
|
|
||||||
char c;
|
|
||||||
|
|
||||||
printf(prefix);
|
printf(prefix);
|
||||||
|
|
||||||
if (!(line = malloc(nalloc_bytes)))
|
if (!fgets(buf, 128, stdin))
|
||||||
return NULL;
|
return NULL;
|
||||||
|
|
||||||
while ((c = getchar()) && c != '\n') {
|
len = strlen(buf);
|
||||||
if (nbytes + 1 >= nalloc_bytes) {
|
|
||||||
nalloc_bytes *= 2;
|
|
||||||
|
|
||||||
if (!(alloc = realloc(line, nalloc_bytes)))
|
if (len > 0 && buf[len - 1] == '\n')
|
||||||
goto err_free_line;
|
buf[len - 1] = '\0';
|
||||||
|
|
||||||
line = alloc;
|
putchar('\n');
|
||||||
}
|
|
||||||
|
|
||||||
line[nbytes++] = c;
|
return buf;
|
||||||
}
|
|
||||||
|
|
||||||
line[nbytes] = '\0';
|
|
||||||
|
|
||||||
return line;
|
|
||||||
|
|
||||||
err_free_line:
|
|
||||||
free(line);
|
|
||||||
return NULL;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void cmd_exec(struct cmd *cmds, const char *line)
|
void cmd_exec(struct cmd *cmds, const char *line)
|
||||||
|
@ -88,6 +75,5 @@ void cmd_loop(const char *show)
|
||||||
while (!should_exit) {
|
while (!should_exit) {
|
||||||
line = prompt(show);
|
line = prompt(show);
|
||||||
cmd_exec(main_cmds, line);
|
cmd_exec(main_cmds, line);
|
||||||
free(line);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Add table
Reference in a new issue