Browse Source

Fixed terminal attributes restoring on exit

Ivan Arkhipov 3 years ago
parent
commit
287e8330e1
1 changed files with 28 additions and 7 deletions
  1. 28 7
      esh_main_loop.c

+ 28 - 7
esh_main_loop.c

@@ -6,9 +6,31 @@
 
 #include "string_misc.h"
 
+#include <signal.h>
+
+struct termios orig_term_attr;
+struct termios new_term_attr;
+volatile sig_atomic_t main_loop_is_running;
+
+void EShRestoreOriginalTerminalConfig() {
+    /* restore the original terminal attributes */
+    tcsetattr(fileno(stdin), TCSANOW, &orig_term_attr);
+}
+
+void EShRunLoopExitSignalHandler(int signum) {
+    EShRestoreOriginalTerminalConfig();
+    main_loop_is_running = 0;
+}
+
 void EShRunLoop() {
-    struct termios orig_term_attr;
-    struct termios new_term_attr;
+    main_loop_is_running = 1;
+    
+    /* registering exit signals */
+    signal(SIGINT, EShRunLoopExitSignalHandler); 
+    signal(SIGQUIT, EShRunLoopExitSignalHandler); 
+    signal(SIGILL, EShRunLoopExitSignalHandler); 
+    signal(SIGABRT, EShRunLoopExitSignalHandler); 
+    signal(SIGKILL, EShRunLoopExitSignalHandler); 
 
     /* set the terminal to semi-raw mode */
     tcgetattr(fileno(stdin), &orig_term_attr);
@@ -16,12 +38,12 @@ void EShRunLoop() {
     new_term_attr.c_lflag &= ~(ECHO | ICANON | ISIG | IEXTEN);
     new_term_attr.c_cc[VTIME] = 0;
     new_term_attr.c_cc[VMIN] = 1;
-    // tcsetattr(fileno(stdin), TCSANOW, &new_term_attr);
+    tcsetattr(fileno(stdin), TCSANOW, &new_term_attr);
 
 	char* command = malloc(esh_info_global->max_command_length);
 	char* uncomplete_command = malloc(esh_info_global->max_command_length); // Used to restore after moves history
 
-	for (;;) {
+	while (main_loop_is_running) {
 		EShShowMsg();
 		memset(command, 0, esh_info_global->max_command_length);
 
@@ -189,8 +211,7 @@ void EShRunLoop() {
 	free(command);
 	free(uncomplete_command);
 
-    /* restore the original terminal attributes */
-    tcsetattr(fileno(stdin), TCSANOW, &orig_term_attr);
+    EShRestoreOriginalTerminalConfig();
 }
 
 void EShShowMsg() {
@@ -452,4 +473,4 @@ void EShPrintJobsDebugInfo(const char* command, EShJob* jobs, int jobs_num) {
 		printf("\n===================\n");
 	}
 	printf("\n");
-}
+}