一,Inotify机制介绍
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/inotify.h>
struct wd_path
{
int wd;
char *path;
};
char * event_array[] = {
"File was accessed",
"File was modified",
"File attributes were changed",
"writtable file closed",
"Unwrittable file closed",
"File was opened",
"File was moved from X",
"File was moved to Y",
"Subfile was created",
"Subfile was deleted",
"Self was deleted",
"Self was moved",
"",
"Backing fs was unmounted",
"Event queued overflowed",
"File was ignored"
};
#define EVENT_NUM 16
int main(int argc,char *argv[])
{
int fd,wd,len,tmp_len,i;
char buffer[1024],*offset,target[1024];
struct wd_path *wd_array;
struct inotify_event *event;
wd_array=(struct wd_path*)malloc((argc-1)*sizeof(struct wd_path));
fd=inotify_init();
if(-1==fd)
{
printf("failed to init inotifyn");
return 0;
}
for(i=0;i<argc-1;i++)
{
wd_array[i].path=argv[i+1];
wd=inotify_add_watch(fd,wd_array[i].path,IN_ALL_EVENTS);
wd_array[i].wd=wd;
}
memset(buffer,0,1024);
while(len=read(fd,buffer,1024))
{
offset=buffer;
event=(struct inotify_event*)buffer;
while(((char *)event-buffer)<len)
{
for(i=0;i<argc-1;i++)
{
if(event->wd==wd_array[i].wd)
{
memset(target,0,1024);
strcpy(target,wd_array[i].path);
strcat(target,"/");
strcat(target,event->name);
printf("nnntarget:%s:n",target);
}
}
for(i=0;i<EVENT_NUM;i++)
{
if(event->mask&(1<<i))
printf(" event:%sn",event_array[i]);
}
tmp_len=sizeof(struct inotify_event)+event->len;
event=(struct inotify_event*)(offset+tmp_len);
offset+=tmp_len;
}
}
return 1;
}
以上代码转自http://my.oss.org.cn/space.php?uid=54816&do=blog&id=87857
二,Inotify-tools工具介绍