The man page for cp(1)
says
--no-clobber
do not overwrite an existing file
However, wouldn't the following scenario be possible?
cp
checks the file existence, let's assume the file doesn't exist (yet)- Some other process writes to the same path, so now there is data written to the previously not existing file
- Since
cp
isn't aware of the now existing file, it overwrites the data
Is cp --no-clobber
vulnerable to this race condition? And if not, how does cp
avoid the situation above?
Best Answer
cp
isn’t vulnerable to this race condition. When--no-clobber
is set, it checks whether the destination already exists; if it determines it doesn’t, and it should therefore proceed with the copy, it remembers that it’s supposed to copy to a new file. When the time comes to open the destination file, it opens it with flags which enforce its creation,O_CREAT
andO_EXCL
; the operating system then checks that the file doesn’t exist while opening it, and fails (EEXIST
) if it does.