title: Ruby: How to acquire file lock for writing?
body: <p>What I want to achieve is this:</p>
  
  <ol>
  <li>if some other process is holding the lock, quit</li>
  <li>otherwise acquire the lock for writing</li>
  </ol>
  
  <p>The Ruby code I am trying to modify is.</p>
  
  <pre><code>File.open(filename, "wb") { |inf|
    if inf.flock(File::LOCK_EX|File::LOCK_NB) == 0
      ...
    end
  }
  </code></pre>
  
  <p>The codes I can find are usually using <code>"rb"</code>. If I change to <code>"wb"</code>, there is a problem: because if some other process is working on the file (which I cannot know until attempting the lock), the file will be wiped out by <code>File.open(..., "wb")</code>.</p>
  
  <p>Is there a way? Thanks.</p>
  
  <h1>New Info</h1>
  
  <p>I think one way is to use <code>"File::RDWR|File::CREAT"</code>, so that you can open file first and it won't wipe out its content, then try the lock. Not sure if there is other way, but <code>"wb"</code> probably will not work. I guess this is an awkwardness of Ruby: you have to open file first before acquiring the lock. I think these two steps should be made atomic.</p>