How could I detect when a directory is mounted with inotify?

后端 未结 5 1687
栀梦
栀梦 2021-02-06 01:58

I\'m using Linux Inotify to detect FS events on my program.

How could I be notified when a device is mounted on a monitored directory?

5条回答
  •  天涯浪人
    2021-02-06 02:56

    inotify only tells you about unmounts, and uevents no longer tells you about mount/unmount.

    The way to do is to poll on /proc/mounts, read in the contents, and keep track of the mounts you've seen, and then reparse when the poll wakes up. The poll will wake up on ERR/PRI when any filesystem is mounted or unmounted.

    #include 
    #include 
    #include 
    #include 
    #include 
    
    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;
    }
    

    The above code just prints out the mount points on startup, and then on any mount/unmount. It's up to you to "diff" them to find out what got added/removed.

    Note, all these techniques has been both unstable and/or broken in past Linux versions. It all got stable around the end of Linux 2.6.35 (or maybe a bit earlier).

提交回复
热议问题