Android native/C/C++ 监控文件夹变化

前言

由于各种原因,总有需求想监听文件夹的变化

实现

实际上Android或者linux提供了inotify接口同来监听文件夹变化

参考代码如下

    int monitorfd; //监听的fd
    int watcher;
    int epollfd; //用epoll来轮询事件
    struct epoll_event event;
    struct epoll_event events[2];
    FILE* fp;
    
    monitorfd = inotify_init(); //初始化监听的fd
    if (-1 == monitorfd) {
        ALOGE("inotify_init error");
        return;
    }
    //把文件夹添加进监听器
    watcher = inotify_add_watch(monitorfd, "/sdcard/", IN_ALL_EVENTS);
    if (-1 == watcher) {
        ALOGE("inotify_add_watch error");
        return;
    }
    //打开监听的fd 准备读取事件
    fp = fdopen(monitorfd, "r");
    if (NULL == fp) {
        ALOGE("fdopen error");
        return;
    }
   
    event.data.fd = monitorfd;
    event.events = EPOLLIN | EPOLLET;  //读入,边缘触发方式
    int ctrl = epoll_ctl(epollfd, EPOLL_CTL_ADD, monitorfd, &event);
    if (-1 == ctrl) {
        ALOGE("epoll_ctl error");
        return;
    }
while (1) {
        int n = epoll_wait(epollfd, events, 5, -1);
        for (int i = 0; i < n; i++) {
            ALOGI("%d, %d, %d", events[i].data.fd, monitorfd, events[i].events);
            if ((events[i].events & EPOLLERR) || (events[i].events & EPOLLHUP) || (!(events[i].events & EPOLLIN))) {
                /* An error has occured on this fd, or the socket is not
                   ready for reading (why were we notified then?) */
                ALOGE("epoll error\n");
                close(events[i].data.fd);
                continue;
            } else if (monitorfd == events[i].data.fd) {
                struct inotify_event ie;
                int read_len = 0;
                while (1) {
                    read_len = fread(&ie, sizeof(ie), 1, fp);
                    if (read_len < 0) {
                        ALOGD("read error %d:%s\n", errno, strerror(errno));
                        break;
                    }
                    ALOGD("%d, %0x, %d\n", ie.wd, ie.mask, ie.len);

                    if (ie.len > 0) {
                        char name[ie.len];
                        read_len = fread(name, ie.len, 1, fp);
                        if (read_len > 0) {
                        //somethine to do
                        }
                    }
                }
            }
        }
    }

你可能感兴趣的:(Android,ROM开发,Android,软件开发,C/C++开发)