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 architecture-independent. Structure passed to fcntl contains fields such as off_t or pid_t. I cannot make assumptions about sizes of those 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) */
...
};
Is there any other way to find the PID? Or maybe sizes of off_t and pid_t? The solution must be fully portable between different architectures.
Edit
I decided to use lsof program as suggested below. Another option is to parse /proc/locks file.
Maybe you can try use external program, lsof, to do that?