Find out how many times a file has been opened

cfilesystemslsofsystem-calls

Ok, here's a brain puzzle: how can I find out how many times a particular file has been opened (in any mode) by any / all processes currently running on a Linux machine? I.e. how many file descriptors, globally (or within a namespace / container, doesn't matter) are in use referencing a particular file / inode?

One way of finding this out would probably be using lsof and counting how many times does the filename in question appears in its output. But that seems inelegant, and in any case, I'd need something like this programatically, in C.

Edit: or maybe a similar but different question, which would also be helpful: is a particular file (a random file on the file system, so no attaching handlers and waiting for something to happen) opened at all, by any process (possibly excluding this one)?

Best Answer

For the currently open files, if on Linux, you'd have to stat() all the /proc/*/fd/* files and compare inode numbers; and read all the /proc/*/maps (and also compare inode numbers).

Check the flags in /proc/*/fdinfo/* (need a relatively recent version of Linux) and the second column in /proc/*/maps for whether the file is open in read or write mode (or both, or with append...).

Related Question