I was wondering how to find out, programmatically, what files are opened by a certain process or if a file is opened by some process. After googling for a while and going through some Linux books, I've found the following references very useful to get a general idea:
- stackoverflow - How to check if a file has been opened by another application in C++
- stackoverflow - How can I tell if a file is open elsewhere in C on Linux?
- book - The Linux Programming Interface, ch. 36, page 762
Here are the solutions that I've found more promising. My target OS was Linux, so if you are looking for a Windows solution, I'd recommend you to look further on the Internet, though some tools listed here will apply to you.
How to tell if a file is opened?
fuser, an external application (only Linux): It allows you to find out the PIDs of the processes which are using the files specified as arguments. Nevertheless, I didn't manage to get any output using fuser -v file on Ubuntu Lucid 10.04.
Handle, an external application (only Windows): You can use it to find both the files opened by a process and the processes which have opened a file (you can use patterns in the search).
How to tell what files has a process opened?
lsof, an external application (only Linux): You can list all the files (not only regular files) opened by a process:
lsof -p `pidof processname` | grep /
Handle for Windows (see above).
/dev/[pid]/fdfolder programmatically (only Linux): It contains several symbolic links to the files opened by the process. You need permission to read the directory (on Ubuntu you only have permission to access the folders of your own processes).
Example terminal command that shows all files opened by a process:
$ for f in $(find /proc/`pidof eclipse`/fd); do readlink $f; done ... /home/david/.mozilla/eclipse/places.sqlite socket: pipe: pipe: anon_inode:[eventpoll] /home/david/Programs/eclipse/plugins/org.eclipse.wst.jsdt.web.ui.jar /home/david/.mozilla/eclipse/permissions.sqlite ...
An explanation to the use of
readlinkfrom TLPI book:
On Linux, we can check which file descriptors a process currently has open by using readdir() to scan the contents of the /proc/PID/fd directory, which contains symbolic links for each of the file descriptors currently opened by the process.