Detecting and deleting a locked file in python

I want to determine if a file is locked using python on Unix. It is normal to delete a file, assuming that it helps determine if the file was locked.

A file could be originally opened exclusively by another process. The documentation seems to suggest that os.unlink will not necessarily return an error if the file is locked.

Ideas?

+3
source share
2 answers

The best way to check if a file is locked is to try to lock it. The fcntl module will do this in Python, for example.

fcntl.lockf(fileobj.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)

This will increase IOError if the file is already locked; if it is not, you can call

fcntl.lockf(fileobj.fileno(), fcntl.LOCK_UN)

To unlock it again.

: Windows, Unix. , fcntl Windows; os.open, , ( ).

+6

fcntl docs:

fcntl.lockf(fd, operation [, length [, start [, whence]]])

LOCK_NB, , IOError , errno, EACCES EAGAIN ( , , ).

unix flock, , , . , os.open, .

+6

Source: https://habr.com/ru/post/1715864/


All Articles