Python - Simulating File Lock

Sometime, it is useful to simulate file lock to test file locking logic. I had tried some Linux command, e.g. flock, which does not work really well.

Below is a Python code that work quite well for me


$ python
Python 2.7.13 (default, Apr  5 2018, 19:36:11)
[GCC 4.1.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import fcntl;
>>> handle = open("/var/abinitio/resource.server.info/server_lock", "a");
>>> fcntl.lockf(handle.fileno(), fcntl.LOCK_EX|fcntl.LOCK_NB);
The above will hold the lock of the file. fuser could see it.

One done, exit Python to remove the lock.

>>> exit()

Comments

Post a Comment

Popular Posts