cp overwrite vs rm then cp
When I try to overwrite a binary file that is currently launched, cp
fails to overwrite, but it's possible to rm
it then cp
. For example:
user@poste:~$ cp binaryFile /tmp
user@poste:~$ sudo cp /tmp/binaryFile binaryFile
[sudo] password for user:
cp: cannot create regular file `binaryFile`: Text file busy
user@poste:~$ sudo rm binaryFile
user@poste:~$ sudo cp /tmp/binaryFile binaryFile
user@poste:~$ file binaryFile
binaryFile : ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.24, BuildID[sha1]=0x7ce005d9eb50e2574246b6a881e625802f7e49f2, not stripped
Any idea why?
In the first case, you're trying to overwrite the contents of a file that is currently running as a program. Linux does not allow that – if it did, you'd overwrite code right as the OS was executing it; the first difference would crash the program or make it malfunction.
But in the second case, you're not actually changing the old file's contents – you're creating a new file in its place, while the old one just loses the filename but keeps its contents untouched.
(Remember that rm
doesn't technically delete files, it just removes directory links – similar to how ln
adds more links to the same file. Only when a file has no links and no open file references, it automatically gets deleted.)
The system references in-use files by their inode, so it doesn't matter that they have the same filename – it's still the old file that remains open by the system, and even though it has no links anymore, it will only get deleted once all programs close it.