Linux Socket Programming-Select

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.