msh

simple shell implementation
Index Commits Files Refs README LICENSE
commit ef1ef26738a7bbd4d8e1245306c89daa0e04feef
parent f0dfe89d1ccfe7ba26fcd91f381475b77387934a
Author: mjkloeckner <martinjkloeckner@gmail.com>
Date:   Sat, 13 May 2023 16:18:50 -0300

set terminal to raw mode during input mode

Diffstat:
Mmsh.c | 9++++++++-
Atui.c | 45+++++++++++++++++++++++++++++++++++++++++++++
Atui.h | 7+++++++
3 files changed, 60 insertions(+), 1 deletion(-)
diff --git a/msh.c b/msh.c
@@ -6,6 +6,8 @@
 #include <sys/types.h>
 #include <sys/wait.h>
 
+#include "tui.h"
+
 #define    READLINE_BUFFER_INIT_SIZE    128
 #define TOKENS_BUFFER_INIT_SIZE        8
 #define TOKENS_DELIM                " |"
@@ -105,15 +107,20 @@ void msh_loop(void) {
     }
 
     while (run) {
+        tui_set_input_mode();
+
         /* make cusor blinking vertical bar */
         printf("\033[5 q$ ");
         buffer = buffer_read_line(buffer);
+
+        tui_reset_input_mode();
+
         tokens = buffer_split(buffer, tokens);
 
         /* skip execute if buffer is empty */
         if(strlen(buffer) > 0)
             msh_execute(tokens);
-
+        
         buffer_clear(buffer);
     }
     free(tokens);
diff --git a/tui.c b/tui.c
@@ -0,0 +1,45 @@
+#include "tui.h"
+
+#include <stdio.h>
+#include <termios.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <signal.h>
+#include <string.h>
+#include <ctype.h>
+
+#define    TAB_SIZE    4
+
+static int is_terminal;
+static struct termios default_attributes;
+
+void tui_reset_input_mode (void) {
+    tcsetattr(STDIN_FILENO, TCSANOW, &default_attributes);
+}
+
+void tui_set_input_mode (void) {
+    struct termios tattr;
+
+    /* Make sure stdin is a terminal. */
+    if (!isatty(STDIN_FILENO)) {
+        is_terminal = 0;
+        return;
+    } else {
+        is_terminal = 1;
+    }
+
+    /* Save the terminal attributes so we can restore them later. */
+    tcgetattr(STDIN_FILENO, &default_attributes);
+    atexit(tui_reset_input_mode);
+
+    /* Set the terminal modes. */
+    tcgetattr(STDIN_FILENO, &tattr);
+
+    tattr.c_iflag &= ~(PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
+    tattr.c_oflag &= ~OPOST;
+    tattr.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
+    tattr.c_cflag &= ~(CSIZE | PARENB);
+    tattr.c_cflag |= CS8;
+
+    tcsetattr(STDIN_FILENO, TCSAFLUSH, &tattr);
+}
diff --git a/tui.h b/tui.h
@@ -0,0 +1,7 @@
+#ifndef __TUI_H__
+#define __TUI_H__
+
+void tui_reset_input_mode(void);
+void tui_set_input_mode (void);
+
+#endif