#include <sys/inotify.h>
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#define INOTIFY_EVENT_ARR_SIZE (1024)
int main(int argc, char *argv[])
{
const char *installlist_path = "/tmp";
int fd, wd, count = 5;
struct inotify_event eventArr[INOTIFY_EVENT_ARR_SIZE];
int eventSize = sizeof(struct inotify_event);
int eventArrSize = eventSize * INOTIFY_EVENT_ARR_SIZE;
do {
if ((fd = inotify_init()) < 0) {
printf("Open file descriptor fail\n");
continue;
}
if ((wd = inotify_add_watch(fd, installlist_path, IN_CREATE | IN_MOVED_TO)) < 0) {
printf("Inotify add watch fail\n");
close(fd);
continue;
}
break;
} while (count--);
if (count < 0) {
printf("exit\n");
return -1;
}
while (1) {
memset(eventArr, 0x00, eventArrSize);
int readLen = read(fd, eventArr, eventArrSize);
if(readLen <= 0) {
printf("Read fail ( Check whether it is interrupted by signal\n");
sleep(1);
continue;
}
int size = readLen / eventSize;
for (int i = 0; i < size; ++i) {
if (eventArr[i].len && (eventArr[i].mask & IN_CREATE)) {
printf("%s/%s\n", installlist_path, eventArr[i].name);
i += (
(eventArr[i].len % eventSize) ?
(eventArr[i].len / eventSize + 1) :
(eventArr[i].len / eventSize)
);
}
}
}
close(fd);
return 0;
}
linux 监听新文件
使用inotify监控文件变化
最新推荐文章于 2024-07-11 14:09:16 发布
本文介绍了一个使用inotify的C程序示例,该程序能够监控指定目录(/tmp)下的文件创建和移动事件。通过inotify_init初始化inotify实例,并使用inotify_add_watch注册监控路径。程序进入循环读取事件,当检测到文件被创建或移动到监控目录时,会打印出相应的文件名。

1003

被折叠的 条评论
为什么被折叠?



