I have implemented a file locking mechanism along the lines of the suggestion from the linux man page for "open", which states:
Portable programs that want to perform atomic file locking using a lockfile, and need to avoid reliance on NFS support for O_EXCL, can create a unique file on the same file system (e.g., incorporating hostname and PID), and use link(2) to make a link to the lockfile. If link(2) returns 0, the lock is successful. Otherwise, use stat(2) on the unique file to check if its link count has increased to 2, in which case the lock is also successful.
This seems to work perfectly, however to get 100% code coverage in my testing, I need to cover the case where the link count is increased to 2.
I've tried googling, but all I seem to be able to find is the same reference above regurgitated as "the way it's done".
Can anybody explain to me what set of circumstances would cause the link to fail (returns -1), but the link count is increased to 2?
The answer to your question is provided at the bottom of the link(2) page of the Linux Programmer's Manual:
On NFS file systems, the return code may be wrong in case the NFS
server performs the link creation and dies before it can say so. Use
stat(2) to find out if the link got created.