title: How do I atomically create a locked file in Linux?
body: <p>Scenario: I have many processes running that need to fetch files over the net. If the file is already downloaded, I want it cached on disk.  If another process is downloading the file, block until it is finished downloading.</p>
  
  <p>I've been trying to find the easiest way to do to this. The obvious way is to:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>This system accomplishes the above goals with (seemingly) no race conditions</p>
  
  <p>Unfortunately, I couldn't find documentation on how to use open(), etc. to create a file that is locked in Linux. If I split the create step into:</p>
  
  <pre><code>open w/ O_CREAT | O_EXCL
  flock
  </code></pre>
  
  <p>a race condition now exists between the create and lock (non-creating process acquires the lock before the creator does).</p>
  
  <p>I realize I could use an external lock file per file (e.g. filename + '.lock), which I acquire before attempting to create filename, but this feels.. inelegant (and I need to now worry about how to files that actually have a .lock suffix!)</p>
  
  <p>Is there anyway to atomically create and lock it (as Windows offers) or is the external lockfile method pretty much what is standard/required? </p>