

The safe way is to create the new file in the same folder as the destination. rename() is only atomic if you do it in the same file system. If the file already exists, the rename will fail and you'll get an error. There is no way to do this file copy operations are never atomic and there is no way to make them.īut you can write the file under a random, temporary name and then rename it. † Step 4 may look unnecessary-why not just use that name in the first place? However, another process may "adopt" your mole file in step 5, and make it the winner in step 7, so it's very important that you're not still writing out the contents! Renames on the same file system are atomic, so step 4 is safe. To prevent this system from livelocking, we add a total ordering on which mole can whack which. If you run this through in your head, you should see that only one mole will ever make it all the way out. Half-way out, it pauses and whacks any competing moles back into the ground, before checking no other mole has fully emerged. Imagine each candidate source file is a mole coming out of its hole. (Don't worry if it's gone, just jump back to step 5.) If you didn't already attempt to delete it in step 6, attempt to rename your temporary file to its final name.Remember your UUID may have changed in step 5.)

If so, attempt to delete your temporary file.
Atom copypath free#
It's an adaptation of the lock-free whack-a-mole algorithm, and not entirely trivial, so feel free to go with "no" as the general answer ) What to do There is in fact a way to do this, atomically and safely, provided all actors do it the same way.
