驱动开发6 IO多路复用——epoll

核心操作:一棵树、一张表、三个接口

相关案例

cs 复制代码
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <sys/ioctl.h>
#include <sys/select.h>
#include <sys/epoll.h>
/* According to earlier standards */
#include <sys/time.h>

int main(int argc, char const *argv[])
{
    int fd1, fd2, epfd;
    struct epoll_event event;      // 用于操作epoll
    struct epoll_event events[10]; // 存放就绪事件描述符的数组
    char buf[128] = {0};
    // 创建epoll句柄
    epfd = epoll_create(1);
    if (epfd < 0)
    {
        printf("epoll_create filed\n");
        exit(-1);
    }
    // 打开设备文件
    fd1 = open("/dev/input/mouse0", O_RDWR);
    if (fd1 < 0)
    {
        printf("打开鼠标设备文件失败\n");
        exit(-1);
    }
    fd2 = open("/dev/mycdev0", O_RDWR);
    if (fd2 < 0)
    {
        printf("打开鼠标设备文件失败\n");
        exit(-1);
    }
    // 添加准备就绪事件进入epoll;
    event.events = EPOLLIN; // 读事件
    event.data.fd = fd1;
    if (epoll_ctl(epfd, EPOLL_CTL_ADD, fd1, &event) < 0)
    {
        printf("epoll_ctl add filed\n");
    }
    event.events = EPOLLIN; // 读事件
    event.data.fd = fd2;
    if (epoll_ctl(epfd, EPOLL_CTL_ADD, fd2, &event) < 0)
    {
        printf("epoll_ctl add filed\n");
    }

    // 监听事件是否发生
    while (1)
    {
        // 如果成功,ret接收返回的事件个数,把就绪的事件放在events数组中
        int ret = epoll_wait(epfd, events, 10, -1);
        if (ret < 0)
        {
            printf("epoll_wait filed\n");
            exit(-1);
        }
        int i;
        // 循环遍历数组,做事件的处理
        for (i = 0; i < ret; i++)
        {
            if (events[i].events & EPOLLIN)//判断发生的事件是不是读事件
            {
                read(events[i].data.fd, buf, sizeof(buf));
                printf("buf:%s\n", buf);
            }
        }
    }
    close(fd1);
    close(fd2);
    return 0;
}

效果呈现

相关推荐
渡我白衣15 分钟前
Linux操作系统之文件(四):文件系统(上)
linux
ZZH1120KQ22 分钟前
Linux系统安全及应用
linux·运维·系统安全
程序漫游人1 小时前
centos8.5安装jdk21详细安装教程
java·linux
小小小糖果人1 小时前
Linux云计算基础篇(5)
linux·运维·服务器
small_wh1te_coder1 小时前
硬件嵌入式学习路线大总结(一):C语言与linux。内功心法——从入门到精通,彻底打通你的任督二脉!
linux·c语言·汇编·嵌入式硬件·算法·c
小张是铁粉1 小时前
docker在Linux的安装遇到的问题
linux·docker·容器
weixin_7714323112 小时前
linux系统 weblogic10.3.6(jar) 下载及安装
linux·运维·jar
绝不偷吃2 小时前
FastDFS分布式储存
linux·nginx
IC 见路不走3 小时前
LeetCode 第91题:解码方法
linux·运维·服务器
翻滚吧键盘4 小时前
查看linux中steam游戏的兼容性
linux·运维·游戏