我想监视我的系统上的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