资源简介
在Linux下,使用inotify机制实时监测文件夹文件变化事件。该源代码已经将该任务编写成了一个线程,方便其他任务调用。
代码片段和文件信息
#include “new_file_monitor.h“
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include nk.h>
#include
#include
#include
#include
#include
#include
#include
#include
void displayInotifyEvent(struct inotify_event *i)
{
if(i->mask & IN_CLOSE) printf(“IN_CLOSE\n“);
if(i->mask & IN_CREATE) printf(“IN_CREATE\n“);
if(i->mask & IN_MOVED_TO) printf(“IN_MOVED_TO\n“);
if(i->len > 0)
{
printf(“name = %s\n“i->name);
}
}
void* file_monitor(void* arg)
{
int inotifyFdwd;
char buf[512];
ssize_t numRead;
char *p;
struct inotify_event *event;
inotifyFd = inotify_init();
if(inotifyFd == -1)
{
printf(“init fail.\n“);
return NULL;
}
wd = inotify_add_watch(inotifyFd NEW_FILE_MONITOR_PATH IN_ALL_EVENTS);
if(wd == -1)
{
printf(“error\n“);
return NULL;
}
while(1)
{
numRead = read(inotifyFdbuf512);
if(numRead == -1)
{
printf(“read error\n“);
continue;
}
for(p=buf;p < buf+numRead;)
{
event = (struct inotify_event *)p;
displayInotifyEvent(event);
p+=sizeof(struct inotify_event) + event->len;
}
}
inotify_rm_watch(inotifyFd wd);
return NULL;
}
int create_new_file_monitor_init(void)
{
int res;
pthread_t one_thread;
pthread_attr_t thread_attr;
res = pthread_attr_init(&thread_attr);
if(res != 0)
{
perror(“Attribute creation failed“);
return -1;
}
res = pthread_attr_setdetachstate(&thread_attr PTHREAD_CREATE_DETACHED);
if(res != 0)
{
perror(“Setting detached attribute failed“);
return -1;
}
res = pthread_create(&one_thread &thread_attr file_monitor NULL);
if(res != 0)
{
perror(“Thread one creation failed“);
return -1;
}
pthread_attr_destroy(&thread_attr);
return res;
}
属性 大小 日期 时间 名称
----------- --------- ---------- ----- ----
文件 168 2018-01-28 18:55 new_file_monitor.h
文件 2308 2018-01-28 18:44 new_file_monitor.c
----------- --------- ---------- ----- ----
2476 2
评论
共有 条评论