Leber
Leber

Reputation: 149

Information about file on Linux system?

I want known if a determinate file is in use by process, i.e. if file is open in read-only mode by that process.

I thought about searching through /proc/[pid]/[fd] directory, but this way I waste a lot of time, and I think that doing this is not beautiful.

Is there any way using some Linux API to determinate if X file is open by any process? Or maybe some structures data like /proc but for files?

Upvotes: 4

Views: 163

Answers (3)

Christopher Neylan
Christopher Neylan

Reputation: 8272

Determining if a process is using a file is easy. The inverse less so. The reason is that the kernel does not keep track of the inverse directly. The information that IS kept is:

  1. A file knows how many links refer to itself (inode table)
  2. A processes knows what files it has open (file descriptor table)

This is why lsof's /proc walking is necessary. The file descriptors in use by a particular process are kept in /proj/$PID (among other things), and so lsof can use this (and other things) to spit out all of the pid <-> fd <-> inode relationships.

This is a nice article on lsof. As with any Linux util, you can always check out its source code for all of the details :)

Upvotes: 2

akappa
akappa

Reputation: 10490

lsof might be the tool you're searching for.

EDIT: I din't realize you are specifically searching for something to be integrated in your application, so my answer appears a little simplistic. But anyway, I think that this question is pretty much related to yours.

Upvotes: 1

Simon Richter
Simon Richter

Reputation: 29578

Not that I know of. The lsof and fuser tools do precisely what you suggest, wander through /proc/*/fd.

Note that it is possible for open files to not have a name, if the file was deleted after being opened, and it is possible for a file to be open without the process holding a file descriptor (through mmap), and even the combination of both (this would be a process-private swap file that is automatically cleaned up on process exit).

Upvotes: 3

Related Questions