Alternatively, you can use the terminal attribute through tcsetattr in termios . If you switch between canonical mode (a new line is required to start the process) and non-canonocal mode (Keypress is more than enough).
The following program works as follows: the process is waiting for user input. If the up arrow key is pressed, it prints the "arrow arrow" and exits. If something else is pressed, it waits for the user to press Enter , and then prints the custom inpu. The outputs after entering inut are printed.
#include <termios.h> #include <unistd.h> #include <fcntl.h> #include <stdio.h> int main() { struct termios oldt, newt; char ch, command[20]; int oldf; tcgetattr(STDIN_FILENO, &oldt); newt = oldt; newt.c_lflag &= ~(ICANON | ECHO); tcsetattr(STDIN_FILENO, TCSANOW, &newt); oldf = fcntl(STDIN_FILENO, F_GETFL, 0); fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK); while(1) { ch = getchar(); if (ch == '\033') { printf("Arrow key\n"); ch=-1; break;} else if(ch == -1) // by default the function returns -1, as it is non blocking { continue; } else { break; } } tcsetattr(STDIN_FILENO, TCSANOW, &oldt); fcntl(STDIN_FILENO, F_SETFL, oldf); if(ch != EOF) { ungetc(ch,stdin);ith putchar(ch); scanf("%s",command); printf("\n%s\n",command); return 1; } return 0; }
source share