注册 登录
编程论坛 Linux系统管理

初步建立一下对 select() 函数的印象_2

madfrogme 发布于 2012-08-30 08:21, 5257 次点击
自己动手,编译运行会发现3秒内不给出数据,select()就会反复不停的执行

然后打印 No data within 3 seconds, 有时候几行简单的实例比文字说明更直观了

程序代码:
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <assert.h>

int main(void) {

    int keyboard;

    int ret, i;

    char c;

    fd_set readfd;

    struct timeval timeout;

    keyboard = open( "/dev/tty", O_RDONLY | O_NONBLOCK);

    assert(keyboard > 0);

    while(1) {

        timeout.tv_sec = 3;

        timeout.tv_usec = 0;

        FD_ZERO(&readfd);

        FD_SET (keyboard, &readfd);

        ret = select ( keyboard + 1, &readfd, NULL, NULL, &timeout);

        if(0 == ret )

            printf("No data within 3 seconds\n");

        if( FD_ISSET ( keyboard, &readfd)) {

            i = read(keyboard, &c, 1);

            if( '\n' == c )

                continue;

            printf("wzj typed '%c'\n", c);

            if('q' == c )

                break;
        }
    }
}
0 回复
1