可以用 Linux 2.6 kenel 提供的 inotify 机制来监控文件系统的变化,例如增加文件,删除文件,修改文件等
下面是一个例子程序,可用来监控一个目录,如果在此目录下进行创建文件、删除文件、修改文件的操作,会有提示信息打印到屏幕上
#include
<
sys
/
inotify.h
>
#include < stdio.h >
#include < errno.h >
#include < sys / types.h >
#include < unistd.h >
#include < sys / ioctl.h >
#define BUF_LEN 4096
int main( int argc, char ** argv)
... {
if(argc < 2) ...{
printf("Usage: %s [directory] ", argv[0]);
return -1;
}
int fd;
fd = inotify_init();
if(fd == -1) ...{
printf("failed in inotify_init, %d ", errno);
return -1;
}
int wd1, wd2;
ADD_AGAIN:
wd1 = inotify_add_watch(fd, argv[1], IN_DELETE|IN_MODIFY|IN_CREATE|IN_IGNORED);
if(wd1 == -1) ...{
perror("inotify_add_watch");
return -1;
} else
printf("new watch fd %d ", wd1);
/**//*
wd2 = inotify_add_watch(fd, "/etc", IN_ACCESS|IN_MODIFY);
if(wd2 == -1) {
perror("inotify_add_watch");
return -1;
}
*/
char buf[BUF_LEN] __attribute__ ((aligned(4)));
ssize_t len, i = 0;
unsigned int queue_len;
int ret;
while (1) ...{
i = 0;
ret = ioctl(fd, FIONREAD, &queue_len);
if(ret < 0) ...{
perror("ioctl");
}
len = read(fd, buf, BUF_LEN);
while(i < len) ...{
struct inotify_event *event = (struct inotify_event*)&buf[i];
printf("wd=%d mask=%d cookie=%d len=%d dir=%s ",
event->wd, event->mask, event->cookie, event->len, (event->mask & IN_ISDIR) ? "yes" : "no");
if(event->len)
printf("name=%s ", event->name);
if(event->mask & IN_IGNORED) ...{
printf("ignored, add again ");
if(0 != inotify_rm_watch(fd, event->wd))
perror("inotify_rm_watch");
goto ADD_AGAIN;
}
i += sizeof(struct inotify_event) + event->len;
}
}
return 0;
}
#include < stdio.h >
#include < errno.h >
#include < sys / types.h >
#include < unistd.h >
#include < sys / ioctl.h >
#define BUF_LEN 4096
int main( int argc, char ** argv)
... {
if(argc < 2) ...{
printf("Usage: %s [directory] ", argv[0]);
return -1;
}
int fd;
fd = inotify_init();
if(fd == -1) ...{
printf("failed in inotify_init, %d ", errno);
return -1;
}
int wd1, wd2;
ADD_AGAIN:
wd1 = inotify_add_watch(fd, argv[1], IN_DELETE|IN_MODIFY|IN_CREATE|IN_IGNORED);
if(wd1 == -1) ...{
perror("inotify_add_watch");
return -1;
} else
printf("new watch fd %d ", wd1);
/**//*
wd2 = inotify_add_watch(fd, "/etc", IN_ACCESS|IN_MODIFY);
if(wd2 == -1) {
perror("inotify_add_watch");
return -1;
}
*/
char buf[BUF_LEN] __attribute__ ((aligned(4)));
ssize_t len, i = 0;
unsigned int queue_len;
int ret;
while (1) ...{
i = 0;
ret = ioctl(fd, FIONREAD, &queue_len);
if(ret < 0) ...{
perror("ioctl");
}
len = read(fd, buf, BUF_LEN);
while(i < len) ...{
struct inotify_event *event = (struct inotify_event*)&buf[i];
printf("wd=%d mask=%d cookie=%d len=%d dir=%s ",
event->wd, event->mask, event->cookie, event->len, (event->mask & IN_ISDIR) ? "yes" : "no");
if(event->len)
printf("name=%s ", event->name);
if(event->mask & IN_IGNORED) ...{
printf("ignored, add again ");
if(0 != inotify_rm_watch(fd, event->wd))
perror("inotify_rm_watch");
goto ADD_AGAIN;
}
i += sizeof(struct inotify_event) + event->len;
}
}
return 0;
}