I have a very simple TCP server written in C. It runs endlessly, waiting for connections. On Windows, I use select to check activity on the socket, and if not, I have the following code allowing me to exit by pressing "q" on the keyboard:
if( kbhit() ) { char c = getch(); if( c == 'q' ) break; }
This does not work on unix, as kbhit does not exist, and getch works differently. I found some sample code that uses tcsetattr to change terminal settings and allow character input by character. After calling the init function, I open / dev / stdin (using O_NONBLOCK ) and read the character, but read( f, &c, 1 ) blocked until the character is printed.
I assume that I could create a separate thread and wait for it indefinitely, and then signal the first thread if the user presses q, but that seems a bit heavy. Of course, is there an easier way?
source share