Select can perceive changes in the set of file descriptors, and if the fd0 (that is, standard input) is placed into the read FD set of SELECT, it is found that only select will return when you press ENTER. Check to set the buffer size of the terminal to 1, so that you can implement the keystroke immediately after the reaction.
#include <stdio.h>#include<stdlib.h>#include<unistd.h>#include<errno.h>#include<termio.h>#include<sys/time.h>#include<sys/types.h>#defineBuf_size 256voidSetup_terminal (structtermios*Old_args);voidReset_terminal (structtermios*Old_args);intMain () {structTermios Old_args; Setup_terminal (&Old_args); Fd_set RfDs; intSres =0; CharBuffer[buf_size]; intNread =0; for (;;) { /*Reset Read File descriptor set*/Fd_zero (&RFDS); /*Add standard input file descriptor to the set*/Fd_set (0, &RFDS); /*Do blocking Select*/printf ("\nselect begin\n"); Sres=Select(0+1, &RFDS, NULL, NULL, NULL); printf ("\nselect return\n"); if(Sres <0) {perror ("Select Error"); Break; } Else if(Sres = =0) { /*should not being here for blocked select without timeout*/printf ("Select timeout\n"); } Else { if(Fd_isset (0, &RfDs)) {Nread= Read (0, Buffer,sizeof(buffer)-1); if(Nread <=0) {perror ("Read Error"); Break; } Buffer[nread]=' /'; printf ("read string (%d):%s\n", nread, buffer); }}} reset_terminal (&Old_args); return 0;}voidSetup_terminal (structtermios*Old_args) {Tcgetattr (0, Old_args); structTermios New_args = *Old_args; New_args.c_lflag&= ~Icanon; New_args.c_cc[vmin]=1; Tcsetattr (0, Tcsanow, &New_args);}voidReset_terminal (structtermios*Old_args) {tcsetattr (0, Tcsanow, Old_args);}
Remember very early also agreed to achieve this function, finally, although with socket programming is not much related.
Reference:
http://tieba.baidu.com/p/685575698