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

效果呈现

相关推荐
Rsingstarzengjx5 小时前
第三十九章 Linux PWM 驱动实验
linux·运维·服务器
SeanQhl6 小时前
BoostKit 环境准备
linux·openeuler·鲲鹏·boostkit·软件源
2601_966492317 小时前
C语言变量揭秘
c语言·变量·编译器·线程安全·内存布局
笔记本note7 小时前
Linux 内存管理
linux·服务器·内存管理
郝学胜-神的一滴8 小时前
Effective STL 条款 14:用扩容函数避免重新分配
linux·开发语言·网络·数据结构·c++·单片机
GeW9 小时前
入行 Linux 与数据库运维:一条路径、三项习惯、一个考证观
linux·数据库
AndreaYYmm10 小时前
SIGUSR2 触发热重载:一个正在抓包的进程如何原子地换掉规则集
c语言·网络协议
2601_9664947210 小时前
C语言是什么
c语言·rust·linux内核·内存管理·系统编程
老师我太想进步了202610 小时前
【数据结构-16】链式二叉树在线OJ题
c语言·数据结构·算法
程序员大阳11 小时前
副队长C语言数据结构教程(4)--双向链表
c语言·数据结构·链表·双向链表