多路复用io接口-select()

io多路转接之系统调用

例: select系统调用的多路转接

#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>

int main(int argc, char* argv[])
{
    fd_set rfds;
    struct timeval tv;
    int retval;
    int nread;
    char buffer[1024];
    char ch;

    /* Watch stdin (fd 0) to see when it has input. */
    FD_ZERO(&rfds);
    FD_SET(STDIN_FILENO, &rfds);

    /* Wait up to five seconds. */
    tv.tv_sec = 5;
    tv.tv_usec = 0;

    retval = select(STDIN_FILENO + 1, &rfds, NULL, NULL, &tv);
    /* Don't rely on the value of tv now! */

    if (retval == -1) {
        perror("select()");
    } else if (retval) {
        /* printf("Data is available now.\n"); */
        if(FD_ISSET(STDIN_FILENO, &rfds)) {
            ioctl(STDIN_FILENO, FIONREAD, &nread);  
            if(nread == 0) {  
                printf("keyboard done\n");  
            } else if(nread > 0) {
                nread = read(STDIN_FILENO, buffer, nread);
                buffer[nread] = '\0';
                printf("STDIN_FILENO: %s\n", buffer);  
            } else { /** nread < 0 **/
                printf("error\n");  
            }
        }
    } else {
        printf("No data within five seconds.\n");
    }
    exit(EXIT_SUCCESS);
}

编译链接执行, 结果如下:

其中, 第一次执行./myselect时键盘没有任何输入, 5秒后打印信息. 第二次执行./myselect时胡乱按一通键盘最后按回车.

 

posted @ 2016-01-16 19:26  zhanglong71  阅读(341)  评论(0编辑  收藏  举报