![](/img/trans.png)
[英]inotify IN_CLOSE_WRITE only detecting files if copied to directory
[英]Does inotify really work for files or only for directories?
我正在嘗試使用inotify
使用以下方法監視對文件/dev/hvc0
更改:
#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
是否也適用於監視文件更改? 還是我做錯了什么?
謝謝!
你缺少增加i
。 在循環結束前添加:
i += EVENT_SIZE + event->len;
如果要監視更改,還需要將讀取/打印操作包裝在無限循環中。
我不明白為什么event->len
返回零可能是因為沒有返回文件名。 但僅出於測試目的,您只需對其進行評論。 在第二點中,您對 i 的處理被破壞了,您永遠不會在循環中將其重置為 0。 這會導致任何后來的 inotify 事件僅在它們比之前最長的事件長時才被考慮,這可能不是您想要的。請在 while 循環中輸入i += EVENT_SIZE + event->len;
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);
while(1)
{
length = read( notify_fd, buffer, BUF_LEN );
if ( length < 0 ) {
perror( "read" );
}
while ( i < length )
{
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);
}
// }
i += EVENT_SIZE + event->len;
}
}
( void ) inotify_rm_watch( notify_fd, wd );
( void ) close( notify_fd);
exit( 0 );
}
根據這個答案,Linux 似乎不會監視特定文件。 如果要收聽特定文件,則應首先收聽其父目錄。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.