2009-07-11 53 views

回答

9

我不认为你可以用inotify来做到这一点。下面是尽管方法:通过Netlink插座

  1. 阅读uevents from kernel并过滤掉那些"ACTION""mount"
  2. Read and parse "/proc/mounts"当你得到一个事件与"mount"行动。
  3. 查找刚刚安装的设备的安装点记录,如果它不是您正在观看的目录,请将其过滤掉。
+0

另一种方法是在'/ etc/mtab'上放置一个'inotify'手表,并且执行与'/ proc/mounts'相同的解析。但这更脆弱。 – 2009-07-11 11:47:37

+0

我不确定现在内核中是否有'uevent'的'mount'动作。看起来它[被认为是坏掉的,并被删除](https://lkml.org/lkml/2006/2/22/169)。 – 2015-07-29 03:32:09

1

如果您不介意很多的虚假警报,您可能可以在/etc/fstab上观看close_nowrite。 。看着/etc/mtab,/proc/mounts等不适合我。

2

在现代的Linux系统的/ etc/mtab中往往指向的/ proc /自/坐骑:

$ ls -l /etc/mtab lrwxrwxrwx 1 root root 12 Sep 5 2013 /etc/mtab -> /proc/mounts $ ls -l /proc/mounts lrwxrwxrwx 1 root root 11 Jul 10 14:56 /proc/mounts -> self/mounts

PROC(5)manpage说,你并不真的需要使用的inotify此文件,它是可轮询:

由于内核版本2.6.15,这 文件是可轮询:在这个文件打开文件进行读取,改变 (即文件系统装载或卸载)导致后选择(2)将文件描述符标记为可读,并且poll(2) 和epoll_wait(2)将文件标记为有错误条件。

有人想知道为什么inotify不能在/ etc/mtab上工作,并找到了这个联机帮助页。

1

inotify只告诉你关于unmounts,并且uevents不再告诉你有关mount/unmount。

要做的方法是在/ proc/mounts上进行轮询,读取内容并跟踪所见的挂载,然后在轮询醒来时进行重新分析。当挂载或卸载任何文件系统时,轮询将在ERR/PRI中唤醒。

#include <fcntl.h> 
#include <errno.h> 
#include <poll.h> 
#include <unistd.h> 
#include <stdio.h> 

int main() 
{ 
    int fd; 
    struct pollfd ev; 
    int ret; 
    ssize_t bytesread; 
    char buf[8192]; 

    fd = open("/proc/mounts", O_RDONLY); 
    printf("########################################\n"); 
    while ((bytesread = read(fd, buf, sizeof(buf))) > 0) 
     write(1, buf, bytesread); 

    do { 

     ev.events = POLLERR | POLLPRI; 
     ev.fd = fd; 
     ev.revents = 0; 
     ret = poll(&ev, 1, -1); 
     lseek(fd, 0, SEEK_SET); 
     if (ev.revents & POLLERR) { 
      printf("########################################\n"); 
      while ((bytesread = read(fd, buf, sizeof(buf))) > 0) 
       write(1, buf, bytesread); 
     } 
    } while (ret >= 0); 
    close(fd); 

    return 0; 
} 

上面的代码只是在启动时打印出安装点,然后在任何mount/unmount上打印出安装点。您可以通过“差异化”来找出增加/删除的内容。

请注意,所有这些技术在过去的Linux版本中都不稳定和/或被破坏。它在Linux 2.6.35的末端(或者更早)可能会稳定下来。