用于监控文件/目录的修改创建删除等操作,也可以配合epoll使用。
#include <stdio.h>
#include <stdlib.h>
#include <error.h>
#include <sys/inotify.h>
#include <string.h>
// #include <unistd.h>
#include "head.h"
#include <iostream>
using namespace std;
#define LOG_TAG "inotify_thread"
#define WATCH_PATH "/home/mi/GitLab/coding/MyProject/test.txt"
void * inotify_thread(void *) {
int fd = -1;
int wd = -1;
char buf[1024] = {0};
fd = inotify_init();
if (fd < 0) {
close(fd);
printf("inotify_init failed!\n");
return NULL;
}
wd = inotify_add_watch(fd, WATCH_PATH, IN_MODIFY | IN_CREATE | IN_DELETE);
if (wd < 0) {
close(wd);
printf("inotify_add_watch failed!\n");
return NULL;
}
static_num++;
cout << "inotify thread static_num = " << static_num << endl;
while (1) {
int result = -1;
struct inotify_event *event = NULL;
struct inotify_event *pos_ev = NULL;
int event_mask = 0;
memset(buf, 0, sizeof(buf));
printf("inotify thread reading ...\n");
result = read(fd, buf, sizeof(buf) -1);
if (result < (int)sizeof(struct inotify_event)) {
printf("could not read event: %s\n",strerror(result));
return NULL;
}
pos_ev = (struct inotify_event *) buf;
while (result >= (int)sizeof(struct inotify_event)) {
event = pos_ev;
event_mask |= event->mask;
printf("%s: read length = %d.\n", LOG_TAG, result);
result -= sizeof(*event);
pos_ev++;
}
switch(event_mask) {
case IN_MODIFY:
printf("%s: modify operation!\n", LOG_TAG);
break;
case IN_CREATE:
printf("%s: create operation!\n", LOG_TAG);
break;
case IN_DELETE:
printf("%s: delete operation!\n", LOG_TAG);
break;
default:
printf("%s: default operation!\n", LOG_TAG);
}
}
inotify_rm_watch(fd, wd);
close(fd);
return NULL;
}
操作文件:
实际输出信息:
可以看到删掉之后再创建和操作就不行了。