is file open in system ? - other than lsof
Nick Craig-Wood
nick at craig-wood.com
Thu Apr 17 12:30:04 EDT 2008
Thomas Guettler <hv at tbz-pariv.de> wrote:
> bvidinli schrieb:
> > is there a way to find out if file open in system ? -
> > please write if you know a way other than lsof. because lsof if slow for me.
> > i need a faster way.
> > i deal with thousands of files... so, i need a faster / python way for this.
> > thanks.
>
> On Linux there are symlinks from /proc/PID/fd to the open
> files. You could use this:
>
> #!/usr/bin/env python
> import os
> pids=os.listdir('/proc')
> for pid in sorted(pids):
> try:
> int(pid)
> except ValueError:
> continue
> fd_dir=os.path.join('/proc', pid, 'fd')
> for file in os.listdir(fd_dir):
> try:
> link=os.readlink(os.path.join(fd_dir, file))
> except OSError:
> continue
> print pid, link
Unfortunately I think that is pretty much exactly what lsof does so is
unlikely to be any faster!
However if you have 1000s of files to check you only need to do the
above scan once and build a dict with all open files in whereas lsof
will do it once per call so that may be a useful speedup.
Eg
------------------------------------------------------------
import os
pids=os.listdir('/proc')
open_files = {}
for pid in sorted(pids):
try:
int(pid)
except ValueError:
continue
fd_dir=os.path.join('/proc', pid, 'fd')
try:
fds = os.listdir(fd_dir)
except OSError:
continue
for file in fds:
try:
link=os.readlink(os.path.join(fd_dir, file))
except OSError:
continue
if not os.path.exists(link):
continue
open_files.setdefault(link, []).append(pid)
for link in sorted(open_files.keys()):
print "%s : %s" % (link, ", ".join(map(str, open_files[link])))
------------------------------------------------------------
You might want to consider http://pyinotify.sourceforge.net/ depending
on exactly what you are doing...
--
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick
More information about the Python-list
mailing list