4 ms·
rename() is an atomic and portable method of file locking that has worked everywhere for 30 years. Just rename a file. If you can stat the file, it hasn't been
by throwawaaarrgh 3y ago
rename() is an atomic and portable method of file locking that has worked everywhere for 30 years. Just rename a file. If you can stat the file, it hasn't been renamed yet. If you try to stat the file and get an error that it doesn't exist, someone already has the lock. When you can stat it, try to rename it; rename will only succeed if your system call successfully renamed it, in which case you have the lock. If rename fails, the lock was taken. Rename the file back to unlock it.
Works on every filesystem because you can't just cache a rename (wouldn't make much sense to try to open a file that doesn't exist after a rename) and you can't have a rename race condition.