我想監視我的系統上的USB密鑰。我知道他們總是安裝在/媒體上,所以我使用inotify監視/媒體。一些USB鑰匙在插入時會創建一個文件夾(例如sda),直到它們被拔出,一些創建一個文件夾(例如sda),立即刪除它並創建一個新文件夾(例如sda1)。這是由於密鑰上的分區造成的。inotify缺失事件
但是,有時inotify只會捕獲創建和刪除第一個文件夾的事件,但會錯過創建第二個文件夾的事件。當我手動檢查/媒體時,第二個文件夾存在,但它從未通過inotify通知。
這種情況很少發生,當它發生時,它總是在重新啓動後第一次插入設備。
#include <sys/inotify.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
/* size of the event structure, not counting name */
#define EVENT_SIZE (sizeof (struct inotify_event))
/* reasonable guess as to size of 32 events */
#define BUF_LEN (32 * (EVENT_SIZE + 16))
int main(int argc, char **argv) {
int fd,wd,len,i;
char buf[BUF_LEN];
struct inotify_event *event;
fd_set watch_set;
fd = inotify_init();
if (fd < 0) {
perror("init failed");
exit(EXIT_FAILURE);
}
wd = inotify_add_watch(fd,"/media",IN_ALL_EVENTS);
if (wd < 0) {
perror("add watch failed");
exit(EXIT_FAILURE);
}
/* put the file descriptor to the watch list for select() */
FD_ZERO(&watch_set);
FD_SET(fd,&watch_set);
while(1) {
select(fd+1,&watch_set,NULL,NULL,NULL);
len = read(fd,buf,BUF_LEN);
i=0;
while(i < len) {
event = (struct inotify_event *) &buf[i];
if ((event->mask & IN_CREATE) != 0) {
printf ("%s created\n",event->name);
}
else if ((event->mask & IN_DELETE) != 0) {
printf ("%s deleted\n",event->name);
}
else {
printf ("wd=%d mask=0x%X cookie=%u len=%u name=%s\n",
event->wd, event->mask,
event->cookie, event->len, event->name);
}
i += EVENT_SIZE + event->len;
}
}
}
任何想法是怎麼回事?
它可以與http://stackoverflow.com/questions/15350369/how-to -use-inotify-in-c是'/ media'被刪除,並且沒有新的'inotify_add_watch'創建新的'/ media'? – 2013-04-04 10:01:58
只有/ media的子文件夾被創建和刪除。雖然一個事件被錯過了,但下一個事件再次被捕獲。所以手錶仍在運行。 – bad 2013-04-04 10:53:03