linux inotify...
时间:2010-08-15 来源:leeshuheng
inotify 是Linux的file system事件通知系统。
用于监测指定目录内文件的创建,删除,修改,访问等操作。
下面的代码是我学习过程中的实验代码,存在错误和不适当的地方。
参考:
inotify(7), Linux内核文档 Documentation/filesystems/inotify.txt
编译:
gcc -g -Wall -Wextra -std=c99 -o mytest main.c
执行
./mytest [指定一个目录]
停止:
Ctrl-C
假定要监测目录/home/mydir,则在一个终端执行:
./mytest /home/mydir
在令一终端执行:
cat > 1.txt;
cat 1.txt;
rm 1.txt;
等命令,就会看到效果。
如果写一个makefile,然后执行make命令,会看到make对各文件的操作过程。
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
main.c:
// 2010年 05月 05日 星期三 08:37:48 CST
// author: 李小丹(Li Shao Dan) 字殊恒(shuheng)
// K.I.S.S
// S.P.O.T
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/inotify.h>
int main(int argc, char *argv[])
{
if(argc != 2) {
fprintf(stderr, "usage: ./mytest directory\n");
exit(1);
}
struct stat st;
if(stat(argv[1], &st) < 0) {
perror(argv[1]);
exit(1);
}
if(!S_ISDIR(st.st_mode)) {
fprintf(stderr, "\'%s\' isn\'t a directory!\n", argv[1]);
exit(1);
}
int fd;
if((fd = inotify_init()) < 0) {
perror("inotify_init");
exit(1);
}
int wd;
if((wd = inotify_add_watch(fd, argv[1], IN_ACCESS |
IN_MODIFY | IN_CREATE | IN_DELETE)) < 0) {
perror("inotify_add_watch");
exit(1);
}
int len, tmp;
char buf[1024];
char *p;
struct inotify_event *inep;
while((len = read(fd, buf, sizeof(buf))) > 0) {
p = buf;
inep = (struct inotify_event *)buf;
while(len >= (int)sizeof(struct inotify_event)) {
if(inep->mask & IN_ACCESS)
printf("Read %s\n", inep->name);
if(inep->mask & IN_MODIFY)
printf("Write %s\n", inep->name);
if(inep->mask & IN_CREATE)
printf("Create %s\n", inep->name);
if(inep->mask & IN_DELETE)
printf("Delete %s\n", inep->name);
tmp = sizeof(struct inotify_event) + inep->len;
inep = (struct inotify_event *)(p += tmp);
len -= tmp;
}
}
inotify_rm_watch(fd, wd);
close(fd);
return 0;
}