Android(安卓)native/C/C++ 监控文件夹变化
16lz
2021-12-04
前言
由于各种原因,总有需求想监听文件夹的变化
实现
实际上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(安卓)中级]Voip之CSipSimple类库的编绎
- 【Unity3d】Unity5与Android交互通信(使用Android(安卓)Studio2.4
- Android常用控件总结
- Android(安卓)requires compiler compliance level 5.0 or 6.0.
- Android中资源文件夹res/raw和assets的使用
- Android传感器应用
- seekBar,RatingBar拖动条
- [Google Android] 理解NDK(1)-- 编译Android(安卓).so文件
- Android(安卓)adb不是内部或外部命令 问题解决