I did something like that (sorry for the French name of some variables)
[code]//The 3 next functions allow the program to do something if a key is pressed
int mygetch(void) {//to get the code of the key that is pressed
struct termios oldt, newt;
int ch;
tcgetattr( STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~( ICANON | ECHO );
tcsetattr( STDIN_FILENO, TCSANOW, &newt ) ;
ch = getchar();
tcsetattr( STDIN_FILENO, TCSANOW, &oldt ) ;
return ch;
}
int mykbhit(void) { //return 1 when a key is pressed
struct timeval tv = {0, 0};
fd_set readfds;
FD_ZERO(&readfds);
FD_SET(STDIN_FILENO, &readfds);
return select(STDIN_FILENO + 1, &readfds, NULL, NULL, &tv) == 1;
}
void mode_raw(int activer) { // to pas the terminal in raw mode. This allows to validate a command wihtout pressing Enter
static struct termios cooked;
static int raw_actif = 0;
if (raw_actif == activer)
return;
if (activer) {
struct termios raw;
tcgetattr(STDIN_FILENO, &cooked);
raw = cooked;
cfmakeraw(&raw);
tcsetattr(STDIN_FILENO, TCSANOW, &raw);
}
else
tcsetattr(STDIN_FILENO, TCSANOW, &cooked);
raw_actif = activer;
}
int main (int argc, char **argv) {
//do something
mode_raw(1); // switch on the raw mode
while(something) {
if(mykbhit())
if (mygetch()==27) { //27 corresponds to the Esc key
mode_raw(0);
break;
}
mode_raw(0); // switch off the raw mode
}[/code]
Thus, if you press the Escape key, the loop will be stopped.
I only tested this way on linux. I do not know for Mac OS or Windows.