linuxC select the function Detailed

select function is cross-platform IO multiplexing function.

His basic idea is to entrust the kernel event monitor to read and write,

This function has an interesting place that uses the structure of a fd_set.

Each call selete function will change the fd_set.

Then go to traverse this fd_set process IO requests.

Every time even while this fd_set reassigned.

The following program to selete function test input console.

There's only one IO object need to listen, rather special.

#include<stdio.h>
#include<unistd.h>
#include<sys/time.h>
#include<sys/select.h>
#define BUF_SIZE 30

int main()
{
    fd_set reads, temp;
    FD_ZERO(&reads);
    FD_SET(0, &reads); // 0 is standard input()
    struct timeval timeout;
    char buf[BUF_SIZE];
    while(1){
        temp = reads;
        timeout.tv_sec = 5;
        timeout.tv_usec = 0;
        int result = select(1, &temp,0,0,&timeout);
        if(result==-1){
            puts("select() error!");
            break;
        }
        else if(result==0){
            puts("Time-out!");
        }
        else{
            if(FD_ISSET(0,&temp)){
                int str_len = read(0, buf, BUF_SIZE);
                buf[str_len] = '\0';
                printf("message from console: %s", buf);
            }
        }
    }
    return 0;
}

 

Guess you like

Origin blog.csdn.net/wwxy1995/article/details/94397613