驱动开发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;
}

效果呈现

相关推荐
顾晨阳——8 分钟前
C/C++字符串
c语言·c++·字符串
算力魔方AIPC11 分钟前
Spec-Kit+Copilot打造AI规格驱动开发
人工智能·驱动开发·copilot
hour_go20 分钟前
Linux Shell 实验一:数据采集与脚本调试错误总结
linux·笔记·bash·shell·实验报告·错误排查
大海里的番茄38 分钟前
随时随地看监控:我的UptimeKuma远程访问改造记
linux·网络
Nix Lockhart1 小时前
《算法与数据结构》第七章[算法4]:最短路径
c语言·数据结构·学习·算法·图论
Sylvan Ding1 小时前
VSCode插件推荐 2025 - 拥抱 Agentic Coding 时代:是时候从 PyCharm 切换到 VSCode 生态了!
ide·vscode·pycharm·extension·插件·agentic·氛围编程
潇湘梦1 小时前
centOS防火墙操作
linux·运维·centos
Aubrey-J1 小时前
Linux中快速部署Elasticsearch(基础&TLS配置)
linux·服务器·elasticsearch
奥尔特星云大使2 小时前
详细的Linux系统更新yum源的教程
linux·运维·服务器·ubuntu·centos·yum源·epel源
lht6319356122 小时前
Ubuntu Server 系统安装图形界面
linux·运维·ubuntu