#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 监听新文件
最新推荐文章于 2024-07-11 14:09:16 发布