我試圖使用inotify
使用監視對文件的更改/dev/hvc0
如下:inotify真的可以用於文件或僅用於目錄嗎?
#include <stdio.h>
#include <sys/inotify.h>
#include <stdlib.h>
#define EVENT_SIZE (sizeof(struct inotify_event))
#define BUF_LEN (1024 * (EVENT_SIZE + 16))
#define WATCH_FILE "/dev/hvc0" /* This file should be present
before this program is run */
int main() {
int notify_fd;
int length;
int i = 0;
char buffer[BUF_LEN];
notify_fd = inotify_init();
if (notify_fd < 0) {
perror("inotify_init");
}
int wd = inotify_add_watch(notify_fd, WATCH_FILE, IN_MODIFY | IN_ACCESS);
int length_read = read(notify_fd, buffer, BUF_LEN);
if (length_read) {
perror("read");
}
while (i < length_read) {
struct inotify_event *event =
(struct inotify_event *) &buffer[i];
if (event->len) {
if (event->mask & IN_ACCESS) {
printf("The file %s was accessed.\n", event->name);
} else if (event->mask & IN_MODIFY) {
printf("The file %s was modified.\n", event->name);
}
}
}
(void) inotify_rm_watch(notify_fd, wd);
(void) close(notify_fd);
return 0;
}
但是,如果文件被訪問/修改,這並不打印。但是,無論何時將要監視的路徑更改爲目錄並更改了文件,它都會打印出發生的正確事件。
inotify
是否也用於監視文件更改?或者我做錯了什麼?
謝謝!
你能再次只是評論檢查長'if(event-> len)'語句用於測試命令。 –
@JKB:gr8,現在工作!但爲什麼'event-> len' 0? o.O – jobin