系统编程之高级文件IO(十四)——select优缺点

一、用select监听多个文件描述符

题目表述:监听鼠标和键盘的变化

标准模板

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


int main(int argc, char const *argv[])
{
    struct timeval time;
    fd_set r_set;
    fd_set all_set;
    time.tv_sec = 3;
    time.tv_usec = 0;
    
    int fd;
    int fds[1024];
    for (size_t i = 0; i < 1024; i++)
    {
        fds[i] = -1;
    }
    
    if((fd = open("/dev/input/mouse0", O_RDWR | O_CREAT, 0655)) < 0)
    {
        perror("open file error!");
        exit(1);
    }
    FD_SET(fd, &r_set);

    for (size_t i = 0; i < 1024; i++)
    {
        if (fds[i] == -1)
        {
            fds[i] = fd;
            break;
        }
        
    }
    
    FD_SET(0, &r_set);

    for (size_t i = 0; i < 1024; i++)
    {
        if (fds[i] == -1)
        {
            fds[i] = 0;
            break;
        }
        
    }

    all_set = r_set;


    while (1)
    {
        r_set = all_set;
        int ret = select(fd + 1, &r_set, NULL, NULL, NULL);

        if (ret == -1)
        {
            perror("select error");
            exit(1);
        }
        
        for (size_t i = 0; i < 1024; i++)
        {
            if (fds[i] != 1)
            {
                if (FD_ISSET(fds[i], &r_set) > 0)
                {
                    if (fds[i] == fd)
                    {
                        int cor;

                        read(fd, &cor, sizeof(cor));

                        printf("cor = %d\n", cor);
                    }
                    else if(fds[i] == 0)
                    {
                        char buffer[1024];

                        read(0, buffer, sizeof(buffer));

                        printf("buffer = %s\n", buffer);
                    }
                    if (--ret == 0)
                    {
                        break;
                    }
                }
            }
        }
    }
    return 0;
}

二、select的优缺点

  • 缺点1
    FD_SET最大1024,如FD_SETSIZE
    最多监听1024,监听范围受限
  • 缺点2
    轮询:全盘轮询;效率最低

优点:可以跨平台(Windows和Linux都可以)

posted @ 2022-04-23 11:24  周末不下雨  阅读(27)  评论(0编辑  收藏  举报