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

發佈了43 篇原創文章 · 獲贊 12 · 訪問量 15萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章