This is a catalog of things UNIX-like/POSIX-compliant operating systems can do atomically, making them useful as building blocks for thread-safe and multi-process-safe programs without mutexes or read/write locks. The list is by no means exhaustive and I expect it to be updated frequently for the foreseeable future.
The philosophy here is to let the kernel do as much work as possible. At my most pessimistic, I trust the kernel developers more than a trust myself. More practically, it’s stupid to spend CPU time locking around an operation that’s already atomic. Added 2010-01-07.
Operating on a pathname
The operations below are best left to local filesystems. More than a few people have written in crying foul if any of these techniques are used on an NFS mount. True. When there are multiple kernels involved, the kernel can’t very well take care of all the locking for us. Added 2010-01-06.
mv -T
atomically changes the target of
to the directory pointed to by
and is indispensable when deploying new code. Updated 2010-01-06: both operands are symlinks. (So this isn’t a system call, it’s still useful.)A reader pointed out thatDeleted 2010-01-06:ln -Tfs
accomplishes the same thing without the second symlink. Added 2010-01-06.strace(1)
shows thatln -Tfs
actually callssymlink(2)
,unlink(2)
, andsymlink(2)
once more, disqualifying it from this page.mv -T
ends up callingrename(2)
which can atomically replace
. Caveat 2013-01-07: this does not apply to Mac OS X, whosemv(1)
doesn’t callrename(2)
.mv(1)
.link(oldpath, newpath)
creates a new hard link callednewpath
pointing to the same inode asoldpath
and increases the link count by one. This will fail with the error codeEEXIST
ifnewpath
already exists, making this a useful mechanism for locking a file amongst threads or processes that can all agree upon the namenewpath
. I prefer this technique fo