以下のサンプル コードは、ファイルの変更を監視します。監視対象のファイルが foo.txt で、サンプル コードから得られたバイナリ名が inotify であるとします。サンプルコードに対して 2 つのテストを行いました。
test1:
1) ./inotify foo.txt
2) echo "hello" > foo.txt
その後、すべて正常に動作し、「file modified」が出力されました。
test2:
1) ./infity foo.txt
2) vim foo.txt
3) 編集して保存しますが、vim を終了しないでください
印刷された行は 不明です マスク 0x00008000、inotify ヘッダー ファイルをチェックアウトすると、このイベント マスクがIN_CLOSE_WRITEを意味することがわかりました.
私の観点からは、「編集して保存」するのは単にメニューを変更するだけです。しかし明らかに、inotify コードには異なる解釈があります。それは私にとって奇妙です、誰かが背後にあることを説明するのを助けることができますか?
#include <sys/inotify.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
int fdnotify = -1;
if (argc !=2) {
fprintf(stderr, "usage: ./inotify dir_name\n");
exit(1);
}
printf("argc is %d\n", argc);
fdnotify = inotify_init();
if (fdnotify < 0) {
fprintf(stderr, "inotity_init failed: %s\n", strerror(errno));
}
int wd = inotify_add_watch(fdnotify, argv[1], IN_MODIFY);
if (wd < 0) {
fprintf(stderr, "inotify_add_watch failed: %s\n", strerror(errno));
}
while(1) {
char buffer[4096];
struct inotify_event *event = NULL;
int len = read(fdnotify, buffer, sizeof(buffer));
if (len < 0) {
fprintf(stderr, "read error %s\n", strerror(errno));
}
event = (struct inotify_event *) buffer;
while(event != NULL) {
if ((event->mask & IN_MODIFY) ) {
printf("File modified %s\n", event->name);
} else {
printf("unknown Mask 0x%.8x\n", event->mask);
}
len -= sizeof(*event) + event->len;
if (len > 0)
event = ((void *) event) + sizeof(event) + event->len;
else
event = NULL;
}
}
}