Windows has an option to open a file with exclusive access rights. Unix doesn't.
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.
The C instruction open( "/var/lock/myLock.lock", O_RDWR | O_CREAT | O_EXCL, 0666 ) returns -1 if the lock file already exist, otherwise it creates it. The function is atomic and ensures there is not race condition.
When the resource is released, the lock file is deleted by the following instruction remove( "/var/lock/myLock.lock" ).
There are two problems with this method.
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.
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.
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.
Here is the list of question I have on this issue:
Q1. Is there a better synchronization method than the lock file ?
Q2. How to determine if the process who created the lock file is still running ?
Q3. How making it possible for another user to remove the lock file if not in use ?
(Code, or link to code, recipes required for accepted answer)
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 accept() in the owner process. Unfortunately, the system wouldn't be atomic anymore.
EDIT: Check my own answer below for the code solution.