简体   繁体   中英

Information about file on Linux system?

I want known if a determinate file is in use by process, ie 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?

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).

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 :)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM