My code needs to go through files in a directory, picking only those, which are currently opened (for writing) by any other process on the system.
The ideal solution would apply for all Unixes, but I'll settle for a Linux-only.
The program is written in Python, but I can add a custom C-function, if I have to -- I just need to know, what API is available for this...
One suggestion I found was to go through all file-descriptors under Linux /proc
, resolving their links to see, if they point at the file of interest. But that seems rather heavy...
I know, for example, that opening a file increases its reference count -- filesystem will not deallocate blocks of an opened file even if it is deleted -- until it is closed -- the feature relied upon by tmpfile(3)
.
Perhaps, a user process can get access to these records in the kernel?
lsof
does this. Download the source forlsof
and read it. – waltinator May 08 '21 at 18:06lsof
does this and probably does it by reading/proc
:) – ilkkachu May 08 '21 at 18:06lsof
-- andfuser
-- scan/proc
. But that yields more information than I need -- I don't care, which processes have the file open. I just want to know, whether any such exist. Perhaps, this information can be obtained more cheaply, than/proc
rescan? – Mikhail T. May 08 '21 at 18:23lsof
on the file and then analyze the return code of said command? – cutrightjm May 09 '21 at 01:50exec
-inglsof
is quite hideous, but, yes, I could do the same scan of/proc
aslsof
appears to be performing. But I'm looking for something less expensive than checking every process whether it has the file open. I know, kernel already has the count inside somewhere. – Mikhail T. May 09 '21 at 03:36