From 87eb989d7975abe52860a6d19aaad3be0a6faeaf Mon Sep 17 00:00:00 2001 From: iridiumR Date: Tue, 20 Sep 2022 21:04:55 +0800 Subject: [PATCH] feat(shell): import readline, and add simple history --- Makefile | 7 ++++--- line.c | 48 ++++++++---------------------------------------- loop.c | 12 +++++++----- 3 files changed, 19 insertions(+), 48 deletions(-) diff --git a/Makefile b/Makefile index 90ea9af..40b0890 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,7 @@ SHELL := /bin/bash CC = gcc SRC = main.c loop.c exec.c line.c builtin.c +LINK= -lreadline OBJ = $(SRC:.c=.ro) DBGOBJ = $(SRC:.c=.do) EXE = dish @@ -11,10 +12,10 @@ debug: CFLAGS = -g -O0 -DDEBUG release: CFLAGS = -Wall -O3 release: $(OBJ) - $(CC) $(CFLAGS) -o $(EXE) $(OBJ) + $(CC) $(CFLAGS) -o $(EXE) $(OBJ) $(LINK) debug: $(DBGOBJ) - $(CC) $(CFLAGS) -o $(DBGEXE) $(DBGOBJ) + $(CC) $(CFLAGS) -o $(DBGEXE) $(DBGOBJ) $(LINK) clean: rm -f *.o *.do *.ro @@ -24,7 +25,7 @@ $(OBJ):$(SRC) rename .o .ro *.o $(DBGOBJ):$(SRC) - $(CC) $(CFLAGS) -c $(SRC) + $(CC) $(CFLAGS) -c $(SRC) rename .o .do *.o c:clean diff --git a/line.c b/line.c index 8df7b91..0a864c5 100644 --- a/line.c +++ b/line.c @@ -1,48 +1,16 @@ /* - * @Author: 1ridic - * @Date: 2022-09-18 14:14:05 - * @Last Modified by: 1ridic - * @Last Modified time: 2022-09-18 14:14:05 + * @Author: 1ridic + * @Date: 2022-09-18 14:14:05 + * @Last Modified by: 1ridic + * @Last Modified time: 2022-09-18 14:14:05 */ -#include "line.h" #include +#include +#include #include #include - -char *readLine(void) { - int bufsize = LINE_BUF_SIZE; - int position = 0; - char *buffer = malloc(sizeof(char) * bufsize); - char c; - - if (!buffer) { - fprintf(stderr, "dish: allocation error\n"); - exit(EXIT_FAILURE); - } - - while (1) { - // read a character - c = getchar(); - // repleace EOF with a null character and return - if (c == EOF || c == '\n') { - buffer[position] = '\0'; - return buffer; - } else { - buffer[position] = c; - } - position++; - - /* if the buffer is full, reallocate */ - if (position >= bufsize) { - bufsize += LINE_BUF_SIZE; - buffer = realloc(buffer, bufsize); - if (!buffer) { - fprintf(stderr, "dish: allocation error\n"); - exit(EXIT_FAILURE); - } - } - } -} +#include +#include "line.h" char **splitLine(char *line) { int bufsize = LINE_BUF_SIZE, position = 0; diff --git a/loop.c b/loop.c index f9edecc..1460839 100644 --- a/loop.c +++ b/loop.c @@ -4,12 +4,14 @@ * @Last Modified by: 1ridic * @Last Modified time: 2022-09-18 23:32:02 */ +#include +#include +#include +#include +#include #include "loop.h" #include "exec.h" #include "line.h" -#include -#include -#include int status; @@ -17,8 +19,8 @@ int loop() { char *line; char **args; - printf(ANSI_COLOR_GREEN"> "ANSI_COLOR_RESET); - line = readLine(); + line = readline(ANSI_COLOR_GREEN"> "ANSI_COLOR_RESET); + add_history(line); args = splitLine(line); status = commandExec(args); free(line);