![](/img/trans.png)
[英]inotify stops monitoring file when the file is deleted and created again
[英]Monitoring file using inotify
我使用inotify監視本地文件,例如“/ root / temp”使用
inotify_add_watch(fd, "/root/temp", mask).
刪除此文件時,將通過read(fd, buf, bufSize)
函數阻止該程序。 即使我創建了一個新的“/ root / temp”文件,程序仍然被讀取函數阻塞。 我想知道inotify是否可以檢測到已創建受監視文件,並且讀取函數可以從fd獲取某些內容,以便不會永久阻止讀取。 這是我的代碼:
uint32_t mask = IN_ALL_EVENTS;
int fd = inotify_init();
int wd = inotify_add_watch(fd, "/root/temp", mask);
char *buf = new char[1000];
int nbytes = read(fd, buf, 500);
我監控了所有事件。
問題是默認情況下read
是一個阻塞操作。
如果您不希望它阻止,請在read
前使用select
或poll
。 例如:
struct pollfd pfd = { fd, POLLIN, 0 };
int ret = poll(&pfd, 1, 50); // timeout of 50ms
if (ret < 0) {
fprintf(stderr, "poll failed: %s\n", strerror(errno));
} else if (ret == 0) {
// Timeout with no events, move on.
} else {
// Process the new event.
struct inotify_event event;
int nbytes = read(fd, &event, sizeof(event));
// Do what you need...
}
注意 :未經測試的代碼。
要查看創建的新文件,您需要查看目錄,而不是文件。 觀察文件時應該看到它被刪除(IN_DELETE_SELF),但是如果創建了一個具有相同名稱的新文件,則可能無法看到該文件。
你應該看一下IN_CREATE |的目錄 IN_MOVED_TO用於查看新創建的文件(或從其他位置移入的文件)。
某些編輯器和其他工具(例如rsync)可能會以不同的名稱創建文件,然后重命名它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.