Python 查找锁定文件的进程的PID
我需要找到谁使用python(posix/linux)锁定了一个文件。目前我使用这种方法:Python 查找锁定文件的进程的PID,python,linux,posix,Python,Linux,Posix,我需要找到谁使用python(posix/linux)锁定了一个文件。目前我使用这种方法: flk = struct.pack('hhqql', fcntl.F_WRLCK, 0, 0, 0, 0) flk = struct.unpack('hhqql', fcntl.fcntl(self.__file, fcntl.F_GETLK , flk)) if flk[0] == fcntl.F_UNLCK: # file is unlocked ... else: pid = fl
flk = struct.pack('hhqql', fcntl.F_WRLCK, 0, 0, 0, 0)
flk = struct.unpack('hhqql', fcntl.fcntl(self.__file, fcntl.F_GETLK , flk))
if flk[0] == fcntl.F_UNLCK:
# file is unlocked ...
else:
pid = flk[4]
此解决方案不是独立于体系结构的。传递给fcntl的结构包含off\u t或pid\t等字段。我无法对这些类型的尺寸进行假设
struct flock {
...
short l_type; /* Type of lock: F_RDLCK,
F_WRLCK, F_UNLCK */
short l_whence; /* How to interpret l_start:
SEEK_SET, SEEK_CUR, SEEK_END */
off_t l_start; /* Starting offset for lock */
off_t l_len; /* Number of bytes to lock */
pid_t l_pid; /* PID of process blocking our lock
(F_GETLK only) */
...
};
有没有其他方法可以找到PID?或者可能是off\u t和pid\t的大小?解决方案必须在不同体系结构之间完全可移植
编辑
我决定按照下面的建议使用lsof程序。另一个选项是解析/proc/locks文件。也许您可以尝试使用外部程序lsof来完成这项工作
我以前使用过
'hhlh'
,因为我认为它最接近跨平台映射到off\t
。但最终我选择了“hhqqh”
,它适用于32位和64位系统
我对这个解决方案感到惊讶,但我所看到的32位框似乎是bits/fcntl.h
使用off64\t
创建flock
结构,除非系统已经定义了\u USE\u FILE\u OFFSET64
(在这种情况下,它只使用常规的'oloff\t
)因此,似乎l\u start
和l\u len
的大小始终是8(python结构格式char'q'
是long
)
这可能不是完全可移植的,我不能说所有的现代32位系统都会这么做,但现在对我来说已经足够好了——所以我想我应该提到它,以防其他人(比如我自己)不必执行另一个进程并进行一系列字符串解析,YMMV。另外,如果我误解(或解释不当)为什么这个格式字符串似乎在两种平台上都能工作-也许有人可以纠正我?pbs模块很适合调用外部实用程序:pbs.lsof(“/path/to/some/file”)
Lsof revision 4.85 lists on its standard output file information
about files opened by processes for the following UNIX dialects:
AIX 5.3
Apple Darwin 9 and Mac OS X 10.[56]
FreeBSD 4.9 and 6.4 for x86-based systems
FreeBSD 8.[02] and 9.0 for AMD64-based systems
Linux 2.1.72 and above for x86-based systems
Solaris 9, 10 and 11