From 70e39a56490162c5ee087dac2d4400d8739f72c4 Mon Sep 17 00:00:00 2001 From: "google-labs-jules[bot]" <161369871+google-labs-jules[bot]@users.noreply.github.com> Date: Wed, 8 Oct 2025 16:44:58 +0000 Subject: [PATCH] feat: add signal handling for Ctrl+C and Ctrl+Z This commit introduces signal handling for SIGINT (Ctrl+C) and SIGTSTP (Ctrl+Z) t - A new "sigint_handler" function is implemented to catch the SIGINT signal. Instead of terminating the shell now clears the current input line and displays a fresh prompt. - The SIGTSTP signal is now ignored, preventing the shell from being suspended with Ctrl+Z. - The signal handlers are registered at the start of the shell's execution. --- Makefile | 2 +- main.c | 3 +++ signals.c | 28 ++++++++++++++++++++++++++++ signals.h | 6 ++++++ 4 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 signals.c create mode 100644 signals.h 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