select和ioctl的一个简单测试

#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/ioctl.h>
#include <sys/types.h> 
#include <sys/socket.h>
/* 标准输入的文件描述符数值 */ #define STDIN 0
int main() {
    struct timeval tv; fd_set readfds;
    /* 设置等待时间为 2 秒零 500,000 微秒 */ tv.tv_sec = 2;
    tv.tv_usec = 500000;
    FD_ZERO(&readfds); FD_SET(STDIN, &readfds);
    /* 因为我们只想等待输入,所以将 writefds 和 execeptfds 设为 NULL */
    /* 程序将会在这里等待 2 秒零 500,000 微秒,除非在这段时间中标准输入有操作 */
    select(STDIN+1, &readfds, NULL, NULL, &tv);
    /* 测试 STDIN 是否在 readfds 集合中 */
    if (FD_ISSET(STDIN, &readfds))
    {
        int status;
        int result = -1;
        status = ioctl(STDIN, FIONREAD, &result);
        /* 在,则在标准输入有输入 */
        printf(" A key was pressed %d 
",result); 
    }
    else
    {
        /* 不在,则在标准输入没有任何输入 */
        printf("Timed out.
");
    }
    return 0;
}

Select()函数可以帮助你同时监视许多套接字。它会告诉你哪一个套接字已经可以读取 数据,哪个套接字已经可以写入数据,甚至你可以知道哪个套接字出现了错误,如果你想 知道的话。 

ioctl 的FIONREAD的这个命令则可以读取缓冲区数据长度

原文地址:https://www.cnblogs.com/zitonglove/p/4974351.html