diff --git a/Makefile b/Makefile index 28fe7d8..5538f97 100644 --- a/Makefile +++ b/Makefile @@ -2,7 +2,7 @@ CC=clang CFLAGS=-Wall -Isrc/include -DDEBUG -g -std=c17 LDFLAGS= FILENAME=myshellin -SRC=src/myshellin.c src/loop.c +SRC=src/myshellin.c src/loop.c src/user.c OBJ=$(SRC:.c=.o) all: myshellin diff --git a/src/include/loop.h b/src/include/loop.h index 87301ec..4543551 100644 --- a/src/include/loop.h +++ b/src/include/loop.h @@ -1,2 +1,3 @@ +void remove_new_line(char *line); void print_input_line(); void loop(); diff --git a/src/include/user.h b/src/include/user.h new file mode 100644 index 0000000..b9b383a --- /dev/null +++ b/src/include/user.h @@ -0,0 +1 @@ +char *get_user(); diff --git a/src/loop.c b/src/loop.c index afbc009..3e744aa 100644 --- a/src/loop.c +++ b/src/loop.c @@ -1,10 +1,18 @@ #define _GNU_SOURCE +#include #include #include +#include #include +#include "user.h" + +void remove_new_line(char* line) { + line[strcspn(line, "\n")] = 0; +} void print_input_line() { - printf("$ "); + char *name = get_user(); + printf("%s $ ", name); } void loop() { @@ -13,6 +21,23 @@ void loop() { while (1) { print_input_line(); - getline(&line, &buffer_size, stdin); + if (getline(&line, &buffer_size, stdin) == -1) { + if (feof(stdin)) { + // the stdin was closed, this usually happens for CTRL-D + printf("\n"); + exit(EXIT_SUCCESS); + } + else { + perror("Error: "); + printf("\n"); + exit(EXIT_FAILURE); + } + } + + remove_new_line(line); + + if (strcmp(line, "quit") == 0) { + break; + } } } diff --git a/src/user.c b/src/user.c new file mode 100644 index 0000000..50f2922 --- /dev/null +++ b/src/user.c @@ -0,0 +1,9 @@ +#include +#include +#include + +char *get_user() { + struct passwd *pass; + pass = getpwuid(getuid()); + return pass->pw_name; +}