From e5ba2b93037facf4338353f52a742d1baf4ffb28 Mon Sep 17 00:00:00 2001 From: Adrien Bourmault Date: Thu, 8 Jul 2021 19:11:56 +0200 Subject: [PATCH] getch ! --- src/cli.c | 47 ++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 44 insertions(+), 3 deletions(-) diff --git a/src/cli.c b/src/cli.c index 503d79b..e31f662 100644 --- a/src/cli.c +++ b/src/cli.c @@ -25,6 +25,8 @@ #include #include #include +#include +#include #define SEND_BUFFER_SIZE 80 #define RECEIVE_BUFFER_SIZE 80 * 24 @@ -32,6 +34,45 @@ #define SERVER_IP_ADDR "127.0.0.1" #define SERVER_PORT 9000 +static char getch(void) +{ + char buf = 0; + // old terminal + struct termios old = {0}; + + // force flush stdout + fflush(stdout); + + if(tcgetattr(0, &old) < 0) { + printLog("Error getting terminal settings!\n"); + return -1; + } + + old.c_lflag &= ~ICANON; // disable buffered I/O + old.c_lflag &= ~ECHO; // set no echo mode + old.c_cc[VMIN] = 1; + old.c_cc[VTIME] = 0; + + if(tcsetattr(0, TCSANOW, &old) < 0) { + printLog("Error setting terminal settings!\n"); + return -1; + } + + if(read(0, &buf, 1) < 0) { + printLog("Error reading character!\n"); + return -1; + } + + old.c_lflag |= ICANON; // enable buffered I/O + old.c_lflag |= ECHO; // set echo mode + + if(tcsetattr(0, TCSADRAIN, &old) < 0) { + printLog("Error resetting terminal settings!\n"); + return -1; + } + return buf; + } + void connectedCommunication(int sockfd) { char sendBuff[SEND_BUFFER_SIZE], receiveBuff[RECEIVE_BUFFER_SIZE], curChar; @@ -46,7 +87,7 @@ void connectedCommunication(int sockfd) i = 0; // Read command from terminal - while (( curChar= getchar()) != '\n') { + while (( curChar= getch()) != '\n') { // XXX ARROWS sendBuff[i++] = curChar; } @@ -71,10 +112,10 @@ void connectedCommunication(int sockfd) // Detect null-string returned if (receiveBuff[0] == 0) { - printLog("An error occured or invalid command!"); + printLog("An error occured or invalid command!\n"); } - printf("%s\n\n", receiveBuff); + printf("%s\n", receiveBuff); } }