Scenario: I have many processes that need to be downloaded over the network. If the file is already loaded, I want to cache it on disk. If another process is downloading the file, lock it until the download is complete.
I am trying to find the easiest way to do this. The obvious way is:
create file w/ an exclusive lock active on it only if it doesn't exist (O_CREAT | O_EXCL) if file exists already: open file and acquire exclusive lock else: download to newly created file release lock
This system fulfills the above goals with (seemingly) no race conditions
Unfortunately, I could not find the documentation on how to use open (), etc. to create a file that is locked on Linux. If I divided the creation step into:
open w/ O_CREAT | O_EXCL flock
there is now a race condition between creation and locking (the non-creating process gets the lock before the creator does).
I understand that I can use an external lock file for each file (for example, file_name + .lock) that I acquired before trying to create the file name, but that seems .. inelegant (and now I need to worry about how the files are, which the suffix .lock actually has!)
Is there anyway to atomize and block it (as suggested by Windows), or is it an external file locking method to a large extent, which is standard / mandatory?
linux file-io flock fcntl
UsAaR33
source share