diff --git a/Makefile b/Makefile index ced3727..c417be1 100644 --- a/Makefile +++ b/Makefile @@ -3,7 +3,7 @@ CC = gcc CFLAGS = -Wall -g LDFLAGS = -lreadline -OBJS = main.o parser.o builtins.o executor.o prompt.o history.o +OBJS = main.o parser.o builtins.o executor.o prompt.o history.o signals.o TARGET = myshell all: $(TARGET) diff --git a/main.c b/main.c index 5202ce3..4d1ef6a 100644 --- a/main.c +++ b/main.c @@ -5,10 +5,13 @@ #include "builtins.h" #include "prompt.h" #include "history.h" +#include "signals.h" int main() { char *input; + setup_signal_handlers(); + while (1) { input = get_prompt(); // custom prompt with readline diff --git a/signals.c b/signals.c new file mode 100644 index 0000000..c68e4e6 --- /dev/null +++ b/signals.c @@ -0,0 +1,28 @@ +#include +#include +#include +#include + +/* + Signal handler for SIGINT (Ctrl+C). + It clears the current input line and displays a new prompt. +*/ +void sigint_handler(int signo) { + (void)signo; + printf("\n"); + rl_on_new_line(); + rl_replace_line("", 0); + rl_redisplay(); +} + +/* + Sets up the signal handlers for the shell. + - SIGINT (Ctrl+C) is caught to prevent the shell from exiting. + - SIGTSTP (Ctrl+Z) is ignored to prevent the shell from being suspended. + - SIGQUIT (Ctrl+\) is also ignored. +*/ +void setup_signal_handlers(void) { + signal(SIGINT, sigint_handler); + signal(SIGTSTP, SIG_IGN); + signal(SIGQUIT, SIG_IGN); +} \ No newline at end of file diff --git a/signals.h b/signals.h new file mode 100644 index 0000000..407e894 --- /dev/null +++ b/signals.h @@ -0,0 +1,6 @@ +#ifndef SIGNALS_H +#define SIGNALS_H + +void setup_signal_handlers(void); + +#endif \ No newline at end of file