I have a very simple TCP server written in C. It runs indefinitely, waiting for connections. On Windows, I use select
to check for activity on the socket, and if there isn't any, I have the following code to allow me to quit by hitting 'q' on the keyboard:
if( kbhit() ) {
char c = getch();
if( c == 'q' ) break;
}
This doesn't work on unix, since kbhit
doesn't exist and getch
works differently. I found some sample code that uses tcsetattr
to change the terminal settings and allow character-by-character input. After calling the init function, I open /dev/stdin (with O_NONBLOCK
) and read a character, but read( f, &c, 1 )
blocks until a character is hit.
I suppose I could spawn a separate thread and have it wait indefinitely and then signal the first thread if the user hits 'q', but that seems a little heavy-handed. Surely there's an easier way?