Linux inotify

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值