epoll模型添加inotify事件的代码实现

本文介绍了Linux下的inotify工具,用于监视文件系统变化,并展示了如何将其与epoll模型结合,通过代码实现对文件系统事件的高效监控。讨论了inotify的接口、事件结构以及内核工作流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <sys/inotify.h>
#include <sys/epoll.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/ioctl.h>
#include <string.h>
struct inotify_data_type{
    int fd;
    char self_type[16];
};

int main(int argc,char* argv[]){
    if(argc < 2) {
        return 1;
    }
    int inotify_fd = inotify_init();
    if(inotify_fd < 0){
        printf("Create inotify descriptor failed.");
        return 1;
    }
    int *wd = malloc(sizeof(int)*(argc-1));
    int i;
    for(i = 1; i < argc; i++){
        wd[i-1] = inotify_add_watch(inotify_fd,argv[i],IN_CLOSE_WRITE);
        if(wd[i-1] < 0){
            printf("Could not watch dirctory : %s");
            return 1;
        }
    }
    int nb = 1;
    ioctl(inotify_fd,FIONBIO,&nb);

    int epoll_fd = epoll_create(1024);
    if(epoll_fd < 0){
        printf("Create epoll descriptor failed");
        return 1;
    }

    struct inotify_data_type inotify_data;
    inotify_data.fd = inotify_fd;
    strcpy(inotify_data.self_type,"inotify");


    struct epoll_event inotify_event;
    int option = EPOLL_CTL_ADD;
    inotify_event.events = EPOLLIN|EPOLLET;
    inotify_event.data.ptr = &inotify_data;

    int result = epoll_ctl(epoll_fd, option, inotify_fd, &inotify_event);
    if(result < 0){
        printf("Could not add Inotify event in EPOLL");
        return 1;
    }

    int running = 1;
    struct epoll_event event_list[10];
    while(running){
        int events_num = epoll_wait(epoll_fd, event_list,10,0);
        if(events_num < 0){
            printf("Epoll_wait failed!");
            return 1;
        }

        if(events_num > 0){
        //  int i = 0;
            for(i = 0; i < events_num; i++){
                struct inotify_data_type *inotify_data_backup = event_list[i].data.ptr;
                if(strcmp(inotify_data_backup->self_type,"inotify") == 0){
                    int revents = event_list[i].events;
                    if(re
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值