filelock
filelock copied to clipboard
Function to check if a a file is locked by another process, and if yes, which process
Useful for https://github.com/r-lib/pkgdepends/issues/141, then we can print out the pid of the other process.
Windows: https://www.codeproject.com/KB/shell/OpenedFileFinder.aspx?fid=422864&df=90&mpp=25&noise=3&sort=Position&view=Quick&fr=26&select=2277170
Unix: see lslocks or lsof or lslk source code, maybe.
To check if a file is locked on Unix, the fcntl API can be used. In R, there does not seem to be a way to call fcntl directly, but in python it works like this:
def locked(fname):
with open(fname, "r") as fd:
ask_lock = struct.pack("hhllhl", fcntl.F_WRLCK, 0, 0, 0, 0, 0)
answer_raw = struct.unpack("hhllhl", fcntl.fcntl(fd, fcntl.F_GETLK, ask_lock))
return answer_raw[0] != fcntl.F_UNLCK
I'm not aware of a general mechanism to find out which process is holding the lock on Unix. lslocks and lsof can only show local processes, not processes on other machines for network filesystems like NFS or GPFS, and I'm not aware of APIs to obtain the other machine/process which holds locks in these cases (but fcntl does show that the file is locked when the filesystem has remote locking support like NFS4 or GPFS).