title: Optimal lock file method
body: <p>Windows has an option to open a file with exclusive access rights. Unix doesn't. </p>
  
  <p>In order to ensure exclusive access to some file or device, it is common practice in Unix to use a lock file usually stored in the /var/lock directory. </p>
  
  <p>The C instruction <code>open( "/var/lock/myLock.lock", O_RDWR | O_CREAT | O_EXCL, 0666 )</code> returns -1 if the lock file already exist, otherwise it creates it. The function is atomic and ensures there is not race condition. </p>
  
  <p>When the resource is released, the lock file is deleted by the following instruction
  <code>remove( "/var/lock/myLock.lock" )</code>.</p>
  
  <p>There are two problems with this method. </p>
  
  <ol>
  <li><p>The program may terminate without removing the lock. For instance because it is killed,  crashes or whatever. The lock file remains in place, and will prevent any access to the resource even though it is not used anymore. </p></li>
  <li><p>The lock file is created with group and world write privilege but it is a common practice to configure accounts to use a permission mask that will clear the group and world write permission. Thus, if we had a reliable method to determine that the lock is orphan (not use), a user not owner of the file will not be allowed to remove it. </p></li>
  </ol>
  
  <p>For the record, I use the lock file to ensure exclusive access to the device connected to the serial port (/dev/ttyUSBx in fact). Advisory method, requiring cooperation, is OK. But exclusive access should be ensured between different users. </p>
  
  <p>Is there a better synchronization method than the lock file?  How to determine if the process who created the lock file is still running? 
  How to make it possible for another user to remove the lock file if not in use? </p>
  
  <p>One solution I came up with was to use the file as Unix socket file. If the file exist, try to connect using the file. If it fails, we may assume the owner process of the file is dead. This requires to have a thread looping on socket <code>accept()</code> in the owner process. Unfortunately, the system wouldn't be atomic anymore.</p>