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

效果呈现

相关推荐
我言秋日胜春朝★18 分钟前
【Linux网络编程】基于udp套接字实现的网络通信
linux·网络·udp
看到我,请让我去学习19 分钟前
C++核心编程(动态类型转换,STL,Lanmda)
c语言·开发语言·c++·stl
conkl26 分钟前
Apache网页优化实战指南 - 让网站加载速度提升
linux·运维·服务器·开发语言·阿里云·apache
huangyuchi.1 小时前
【Linux】初见,进程概念
linux·服务器·操作系统·进程·进程管理·pcb·fork
thinkMoreAndDoMore1 小时前
linux驱动开发(9)- 信号量
linux·运维·驱动开发
南菠湾1 小时前
如何在 Visual Studio Code 中配置SSH、Git 和 Copilot插件
git·vscode·ssh
五阿哥爱跳舞2 小时前
【环境配置】解决linux每次打开终端都需要source .bashrc文件的问题
linux·运维·服务器
网易独家音乐人Mike Zhou2 小时前
【Linux应用】Linux系统日志上报服务,以及thttpd的配置、发送函数
linux·运维·服务器·mcu·物联网·嵌入式·iot
Eric.Lee20212 小时前
ubuntu 系统 多条命令通过 bash 脚本执行
linux·ubuntu·bash
程序员打怪兽3 小时前
线程间数据传递机制详解(共享全局内存 + 互斥锁同步)
linux·嵌入式