As already mentioned, you can use sigaction to catch ctrl-c or select to capture any standard input.
Please note, however, that with the latter method, you also need to set TTY so that it works in a "different" mode, not in time. The last one by default - if you enter a line of text, it will not be sent to the running stdin program until you press enter.
You need to use the tcsetattr() function to disable ICANON mode and possibly also disable ECHO. From memory, you must also set the terminal to ICANON mode when the program exits!
Just for completeness, here is some code that I just hit (nb: no error check!) That installs Unix TTY and emulates the DOS <conio.h> kbhit() and getch() :
#include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/select.h> #include <termios.h> struct termios orig_termios; void reset_terminal_mode() { tcsetattr(0, TCSANOW, &orig_termios); } void set_conio_terminal_mode() { struct termios new_termios; /* take two copies - one for now, one for later */ tcgetattr(0, &orig_termios); memcpy(&new_termios, &orig_termios, sizeof(new_termios)); /* register cleanup handler, and set the new terminal mode */ atexit(reset_terminal_mode); cfmakeraw(&new_termios); tcsetattr(0, TCSANOW, &new_termios); } int kbhit() { struct timeval tv = { 0L, 0L }; fd_set fds; FD_ZERO(&fds); FD_SET(0, &fds); return select(1, &fds, NULL, NULL, &tv); } int getch() { int r; unsigned char c; if ((r = read(0, &c, sizeof(c))) < 0) { return r; } else { return c; } } int main(int argc, char *argv[]) { set_conio_terminal_mode(); while (!kbhit()) { /* do some work */ } (void)getch(); /* consume the character */ }
Alnitak Jan 15 '09 at 23:37 2009-01-15 23:37
source share