2012-03-13 77 views
3

我需要找到誰使用python(posix/linux)來鎖定文件。目前我使用這種方法:查找鎖定文件的進程的PID

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_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_t和pid_t的大小?該解決方案必須在不同體系結構之間完全適用於便攜式

編輯 我決定用lsof的程序如下建議。另一種選擇是解析/ proc/locks文件。

回答

4

也許你可以嘗試使用外部程序lsof來做到這一點?

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 
+0

pbs模塊很適合調用外部實用程序:pbs.lsof('/ path/to/some/file') – 2012-03-14 04:28:21

+0

謝謝!完美的作品。 – user1267671 2012-03-17 17:26:09

0

我以前用'hhllh',因爲我認爲這將最密切映射到off_t跨平臺。但最終我解決了'hhqqh',這在32位和64位系統上適用於我。

我對這個解決方案感到驚訝,但似乎是什麼回事了32位箱子,我看到的是bits/fcntl.h創建flock結構與off64_t,除非系統已經定義__USE_FILE_OFFSET64(在這種情況下,它只是使用了正'ol off_t)所以它看起來像l_startl_len的大小總是8(python結構格式char 'q'long long)。

這可能不是完全可移植的,我不能說所有的現代32位系統都會這樣做,但現在對我來說足夠好了 - 所以我想我會提及它以防其他情況(比如我自己)寧願不需要執行另一個進程並執行一堆字符串解析,YMMV。此外,如果我誤解(或不好解釋)爲什麼這種格式的字符串似乎在兩個平臺上工作 - 也許有人可以糾正我?