Reputation: 5892
I need to implement the following functionality
locked = False
while not locked:
file_path = get_file_path_from_poll()
locked = try_lock_file(file_path)
if locked:
# do some staff
locked = True
release_lock(file_path)
How can this be implemented in python? I need to work with Linux files, cause there will be many different processes and each should lock one of the files from some folder
Upvotes: 0
Views: 311
Reputation: 22448
Here are very simplistic examples of using fcntl
https://docs.python.org/3/library/fcntl.html#module-fcntl
The first uses LOCK_NB
to avoid blocking, the second doesn't, which means it will block, waiting for file access.
import fcntl
import time
print('Attempting to lock file')
f = open('./locked.txt', 'w')
fcntl.flock(f.fileno(), fcntl.LOCK_EX|fcntl.LOCK_NB)
print ('Lock Acquired')
f.write("some text")
print('Attempting 2nd lock')
f2 = open('./locked.txt', 'r')
f2_locked = False
try:
fcntl.flock(f2.fileno(), fcntl.LOCK_EX|fcntl.LOCK_NB)
except BlockingIOError:
print ('The file is Locked 2')
f2_locked = True
print('Sleeping with file locked')
print('Run this program from another terminal to test')
time.sleep(15)
print('File closed try again')
f.close()
time.sleep(15)
This example blocks, waiting for file access
import fcntl
import time
print('Attempting to lock file')
f = open('./locked.txt', 'w')
fcntl.flock(f.fileno(), fcntl.LOCK_EX)
print ('Lock Acquired')
f.write("some text 2")
print('Sleeping with file locked')
print('Run this program from another terminal to test')
time.sleep(15)
print('File closed try again')
f.close()
time.sleep(15)
Upvotes: 1