From 7c0c74c0a91492219b7ffb687235cd1094dfc6a4 Mon Sep 17 00:00:00 2001 From: g1n Date: Mon, 27 Sep 2021 15:17:59 +0300 Subject: [PATCH] Add proper signal handling and add readline support --- src/Makefile | 2 +- src/main.c | 28 ++++++++++++++++++---------- 2 files changed, 19 insertions(+), 11 deletions(-) diff --git a/src/Makefile b/src/Makefile index 12bbfe1..056781e 100644 --- a/src/Makefile +++ b/src/Makefile @@ -1,5 +1,5 @@ CC = gcc -CFLAGS= -O2 -Wall -Wextra +CFLAGS= -O2 -Wall -Wextra -lreadline LFLAGS= SRCFILES= main.c diff --git a/src/main.c b/src/main.c index 1a2d19e..3ad05e9 100644 --- a/src/main.c +++ b/src/main.c @@ -6,6 +6,8 @@ #include #include #include +#include +#include int position = 0; char pwd[128]; // FIXME: change to PATH_MAX @@ -13,6 +15,7 @@ char hostname[1024]; // Hostname of machine struct passwd *pw; // Struct of passwd for uid char *username; // Current username char *homedir; // HOME directory of current user +pid_t shell_pid; // pid of current shell (gets only on start) pid_t pid; // FIXME: this shouldn't be global i think char **split_line(char *line, char *delim) { @@ -140,27 +143,34 @@ void init() { // Some initial tasks pw = getpwuid(getuid()); // Get passwd struct for current uid username = pw->pw_name; homedir = pw->pw_dir; + shell_pid = getpid(); } void print_ps() { // TODO: add parsing config file + // FIXME: add proper PS1 (this is commented because of readline currently) + /* if (!strcmp(pwd, homedir)) { printf("%s@%s %s> ", username, hostname, "~"); - } else + } else { printf("%s@%s %s> ", username, hostname, basename(pwd)); + }*/ + printf("orsh> "); } void signal_handler(int sig) { - if (pid == 0) - raise(sig); - else + if (pid == 0) { printf("\n"); + print_ps(); + } else if (shell_pid == getpid()) { // Do nothing because readline prints the prompt + } else + raise(sig); + } int main(int argc, char *argv[]) { char *line = NULL; char script_line[100]; // FIXME - size_t len = 0; init(); char** commands; char** args; @@ -180,13 +190,11 @@ int main(int argc, char *argv[]) { } else { while(1) { - print_ps(); // Prints PS1 (TODO: also should print PS2 and so on if it is required) - status = getline(&line, &len, stdin); - if (status == EOF) { - printf("\nexit\n"); + line = readline("orsh> "); // FIXME: add prompt + if (line == NULL) { + printf("exit\n"); break; } - line[strlen(line) - 1] = '\0'; commands = split_line(line, ";"); int after_parse_position = position; // To know where we in ; list FIXME for (int i = 0; i <= after_parse_position - 1; i++) {