Results 1 to 3 of 3
Hello!
I'm trying to write a script that I could run in tty, which will basically just react to any (keyboard)input.
The most obvious choice would be using read of ...
- 07-11-2011 #1Just Joined!
- Join Date
- Mar 2010
- Posts
- 8
Shell script to react on any user input
Hello!
I'm trying to write a script that I could run in tty, which will basically just react to any (keyboard)input.
The most obvious choice would be using read of course, but it doesn't seem to do what I want, as it seems to wait for me to press enter.
I'd like to get a reaction from any keypress. Does anyone know any way to do this? If not in bash, then perhaps in c or c++ - remember that this is without an Xorg server.
Cheers!
- 07-11-2011 #2Just Joined!
- Join Date
- Mar 2007
- Location
- Bogotá, Colombia
- Posts
- 39
I think you can use the C function getchar().
- 07-11-2011 #3
It's a bit more complicated than saying "use getchar()"...
If I understand the original question, what's needed is for the script to respond to any keypress. But there's a fundamental obstacle there: the terminal driver, by default, line-buffers its input. (This is known as "cooked mode" - in this mode the terminal will also react to presses of keys like CTRL-C or CTRL-Z by issuing the appropriate signals to the foreground process group.)
To get around that, you need to switch the terminal to either raw mode (in which the application has full, direct access to the keyboard input) or cbreak (very similar to raw mode, except special keystrokes are still handled normally.) Using a TTY library like Curses makes that reasonably simple:
Doing it yourself without Curses is a little bit complicated. You'd use tcgetattr and tcsetattr to get to raw or cbreak mode - it's a bit involved and honestly I haven't taken the time to learn all the ins and outs of doing it.Code:#include <curses.h> int main() { initscr(); // Start curses cbreak(); // Turn off TTY buffering noecho(); // Turn off TTY input echo getch(); // Read a character from the TTY endwin(); // Shut down Curses }


Reply With Quote