How to monitor changes to pseudo-filesystem on Linux?

Viewed 25

As neither dnotify nor inotify is able to monitor changes to pseudo-filesystem content is there an automated way to discover file/directory creation/deletion inside (for example) /sys/block directory?

Of course, I can scan the directory periodically on my own but hope that there is a smarter way.

1 Answers

I decided to use a somewhat naive workaround and monitor /dev directory (which is supported by inotify) instead of /sys/block. Fortunately, each /sys/block entry has its counterpart inside /dev (but not vice versa) so I just check whether an entry that appeared in /dev is also present inside /sys/block.

Not very elegant but sufficient for me.

#include <stdio.h>
#include <sys/inotify.h>
#include <unistd.h>
#include <assert.h>
#include <linux/limits.h>
#include <sys/stat.h>

int main(void) 
{
        int fd = inotify_init();
        assert(fd >= 0);

        int wd = inotify_add_watch(fd, "/dev", IN_CREATE);
        assert(wd >= 0);

        for(;;) {
            char _event[sizeof(struct inotify_event) + NAME_MAX + 1];
            int res = read(fd, _event, sizeof(_event));
            assert(res > 0);
            struct inotify_event *event = (struct inotify_event *) _event;
            if(event -> len > 0 && event -> mask & IN_CREATE && !(event -> mask & IN_ISDIR)) {
                char dev_name[NAME_MAX + 1];
                sprintf(dev_name, "/sys/block/%s/stat", event -> name);
                struct stat statbuf;
                if(0 == stat(dev_name, &statbuf))
                    printf("new entry appeared: %s\n", event -> name);
            }
        }
}
Related