Python – Find the PID of the process that locked the file

Find the PID of the process that locked the file… here is a solution to the problem.

Find the PID of the process that locked the file

I need to find who locked a file using python (posix/linux). Currently I use this method:

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]

This solution is not schema-independent. The structure passed to FCNTL contains fields such as off_t or pid_t. I can’t make assumptions about the size of these types.

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) */
    ...
};

Are there other ways to find PID? Or the size of off_t and pid_t? The solution must be fully portable across different architectures.

Edit
I decided to use the lsof program as suggested below. Another option is to parse the /proc/locks file.

Solution

Maybe you can try to do this with an external program 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

Related Problems and Solutions