我想监视系统上的USB密钥。我知道它们总是安装在/ media中,因此我使用inotify监视/ media。一些USB钥匙在插入时会创建一个文件夹(例如sda),直到拔出它们为止,而另一些会创建一个文件夹(例如sda),立即将其删除并创建一个新文件夹(例如sda1)。那是由于键上的分区。
但是,有时inotify仅捕获创建和删除第一个文件夹的事件,而错过第二个文件夹的创建。当我手动检查/ media时,第二个文件夹存在,但是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 …Run Code Online (Sandbox Code Playgroud)