Hi list!

This is more a general POSIX question but I guess here I have the best
chance to get a definite answer.

If I want to replace a file with another file without removing the first
one and without having a moment in time at which the file name does not
exist, I can use the following sequence:

# swap $file1 with $file2 on the same file system
dir=$(dirname "$file1")
tmp=$(mktemp -u -d "$dir") # [1]
ln "$file1" "$tmp"
mv "$file2" "$file1"
mv "$tmp" "$file2"

This works because mv does not affect the hardlink to $file1 and a
rename operation on a single file system is atomic. This is a handy
procedure when you have a background process which occasionally opens
$file1 and you don't want it to fail just because of bad timing.

Now my question is: How can I do a similar thing for a directory? I
cannot usually create hardlinks on directories (are there file systems
where this actually works?) and I cannot use mv to overwrite one
directory with another.

The only idea I currently have is to create a level of indirection via
symlinks and then atomically overwrite the symlink. Is there any other way?

[1] Yes, I know I need to iterate this and the next line in case a
different process creates $tmp in between syscalls. Putting in a few -T
and "--" switches might also help but let's keep it simple for the moment.

Thanks in advance!
Florian Philipp

Attachment: signature.asc
Description: OpenPGP digital signature

Reply via email to