title: File r/w locking and unlink
body: <p>I have following problem. I want to create a file system based session storage where each session data is stored in simple file named with session ids.</p>
  
  <p>I want following API: <code>write(sid,data,timeout)</code>, <code>read(sid,data,timeout)</code>, <code>remove(sid)</code>
  where sid==file name, Also I want to have some kind of GC that may remove all timed-out sessions.</p>
  
  <p>Quite simple task if you work with single process but absolutly not trivial when working with multiple processes or even over NFS.</p>
  
  <p>The simplest solution I thought about was:</p>
  
  <pre><code>write/read:
     fd=open(file_name,O_CREAT | O_RDWR); // create a new file or use exsting
     fcntl_lock_file(fd)
     save data to fd/read data from fd
     fcntl_unlock_file(fd)
     close(fd)
  
  GC:
     fd=open(file_name,O_RDWR);
     fcntl_lock_file(fd)
     if(timed_out)
        unlink(file_name)
     fcntl_unlock_file(fd)
     close(fd)
  </code></pre>
  
  <p>The biggest issue that file unlinking works on file names and file locks work on file
  descriptors. So the above would not work in following scenario:</p>
  
  <pre><code>GC - open,
  write - open
  GC - lock, unlink, unlock, close // file still exists because held by write
  write - lock, write, unlock, close // file removed
  </code></pre>
  
  <p>Does anybody have an idea how such issue may be solved? Are there any tricks that allow
  combine file locking and file removal or make operation on file atomic?</p>
  
  <p><strong>Notes:</strong></p>
  
  <ul>
  <li>I don't want to use Database,</li>
  <li>I look for a solution for Unix</li>
  <li>Solution should work with standard POSIX calls like fcnl, open, close, unlink</li>
  </ul>
  
  <p>Thanks.</p>
  
  <p><strong>Clearification</strong> the major issue is that operation on files (names -- unlink) should be done atomically with operation of file descriptors -- locking:</p>
  
  <ul>
  <li>open, unlink -- work on files</li>
  <li>fnctl -- work on descriptors</li>
  </ul>