Comment detail

ファイル更新の監視 (Nested Flatten)
最近のLinux用。 ファイル更新の定義が謎なのでいろいろ監視します。いろいろには、内容の変更、属性の変更、移動、削除が含まれます。ファイルを移動したりファイル名をリネームしても対象ファイルの監視を続けます。対象ファイルが削除されると監視をやめます。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/* $ gcc fnotify.c -o fnotify -Wall */
#include <sys/inotify.h>
#include <unistd.h>
#include <limits.h>
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>

#define INOE_HDR_SZ offsetof(struct inotify_event, name)

static int ino_error(int ino_dev, const char *message)
{
    close(ino_dev);
    perror(message);
    return EXIT_FAILURE;
}

int observe(const char *filename)
{
    int ino_dev, ino_fd, len;
    struct inotify_event *event;
    char buffer[INOE_HDR_SZ + PATH_MAX];
    
    ino_dev = inotify_init();
    if (ino_dev == -1) {
        perror("inotify_init");
        return EXIT_FAILURE;
    }
    ino_fd = inotify_add_watch(ino_dev, filename,
                IN_ATTRIB | IN_MODIFY | IN_MOVE_SELF | IN_DELETE_SELF);
    if (ino_fd == -1) {
        return ino_error(ino_dev, filename);
    }
    event = (struct inotify_event *)buffer;
    
    while (1) {
        len = read(ino_dev, event, sizeof(buffer));
        if (len == -1 || len == 0) {
            return ino_error(ino_dev, "read");
        }
        if (event->mask & IN_ATTRIB) {
            puts("modified! (ATTRIB)");
        } else if (event->mask & IN_MODIFY) {
            puts("modified! (MODIFY)");
        } else if (event->mask & IN_MOVE_SELF) {
            puts("modified! (MOVE_SELF)");
        } else if (event->mask & IN_DELETE_SELF) {
            puts("modified! (DELETE_SELF)");
            break;
        }
    }
    close(ino_dev);
    
    return EXIT_SUCCESS;
}

int main(int argc, const char **argv)
{
    if (argc != 2) {
        fprintf(stderr, "Usage: %s filename\n", argv[0]);
        return EXIT_FAILURE;
    }
    
    return observe(argv[1]);
}

Index

Feed

Other

Link

Pathtraq

loading...