Linux file information?

I want to know if a deterministic file is used by process, i.e. if the file is open in read-only mode by this process.

I was thinking about searching through the / Proc / [PID] / [FD] directory, but this way I spend a lot of time, and I think doing it is not beautiful.

Can any Linux API be used to determine if an X file is open by a process? Or maybe some structure data like / proc, but for files?

+4
source share
3 answers

Determining that a process is using a file is simple. The converse is less. The reason is that the kernel does not track the reverse directly. The information that is stored is as follows:

  • The file knows how many links refer to itself (inode table)
  • Processes know which files are open (file descriptor table)

This is why lsof / proc walking is required. The file descriptors used by a particular process are stored in / proj / $ PID (by the way), and therefore lsof can use this (and other things) to spill out all pid ↔ fd ↔ inode.

This is a good article on lsof . Like any other Linux, you can always check its source code for all the details :)

+2
source

Not that I knew. The lsof and fuser tools do exactly what you suggest; wander around /proc/*/fd .

Please note: it is possible that open files do not have a name if the file was deleted after it was opened, and you can open a file without a process with a file descriptor (via mmap ), and even a combination of both (this will be a private process substitution file, which is automatically cleared when process output).

+3
source

lsof may be the tool you are looking for.

EDIT . I don’t understand that you are specifically looking for something that needs to be integrated into your application, so my answer seems a bit simplified. But in any case, I think this question is largely related to yours.

+1
source

Source: https://habr.com/ru/post/1387406/


All Articles