Introducing File::Symlink::Atomic

In Tips & tricks from my 4 months at Pythian, I showed how to give a symlink a new target atomically. I wasn't aware of any module to encapsulate that, so I quickly put together File::Symlink::Atomic.

This module is useful because it eliminates the need to know how to do this safely - simply

use File::Symlink::Atomic

and you get a drop-in replacement for CORE::symlink. It creates a temporary symlink (using File::Temp to get a unique pathname) pointing to your new target, then moves it into place with a rename call. On POSIX systems, the rename system call guarantees atomicity.

I put it on PrePAN to get some advice. I have no clue what that'll do on any non-POSIX systems that have symlinks (if the OS doesn't do symlinks, I can't help you). Is a rename call universally atomic? If not, how can I detect those platforms, and provide that atomic guarantee some other way?

I didn't get any feedback, so I chose to simply release the module. It's now on CPAN. Enjoy!

Comments
Comment from Kushal Kumaran - May 29, 2012 at 9:07 am

The rename operation can fail if source and destination are not in the same filesystem. mv works by reading the source, writing to the destination, and then deleting the source, if the two are in different filesystems.

For atomicity purposes, it is sufficient to keep $tmp_symlink_name in dirname($symlink_name).