Reputation: 28121
In windows, if I open a file with MS Word, then try to delete it. The system will stop me. It prevents the file being deleted.
There is a similar mechanism in Linux? How can I implement it when writing my own program?
Upvotes: 3
Views: 2435
Reputation: 56048
There is not a similar mechanism in Linux. I, in fact, find that feature of windows to be an incredible misfeature and a big problem.
It is not typical for a program to hold a file open that it is working on anyway unless the program is a database and updating the file as it works. Programs usually just open the file, write contents and close it when you save your document.
vim
's .swp
file is updated as vim works, and vim holds it open the whole time, so even if you delete it, the file doesn't really go away. vim
will just lose its recovery ability if you delete the .swp
file while it's running.
In Linux, if you delete a file while a process has it open, the system keeps it in existence until all references to it are gone. The name in the filesystem that refers to the file will be gone. But the file itself is still there on disk.
If the system crashes while the file is still open it will be cleaned up and removed from the disk when the system comes back up.
The reason this is such a problem in Windows is that mandatory locking frequently prevents operations that should succeed from succeeding. For example, a backup process should be able to read a file that is being written to. It shouldn't have to stop the process that is doing the writing before the backup proceeds. In many other cases, operations that should be able to move forward are blocked for silly reasons.
Upvotes: 5
Reputation: 23542
The semantics of most Unix filesystems (such as Linux's ext2 fs family) is that a file can be unlink(2)
'd at any time, even if it is open. However, after such a call, if the file has been opened by some other process, they can continue to read and write to the file through the open file descriptor. The filesystem does not actually free the storage until all open file descriptors have been closed. These are very long-standing semantics.
You may wish to read more about file locking in Unix and Linux (e.g., the Wikipedia article on File Locking.) Basically, mandatory and advisory locks on Linux exist but they're not guaranteed to prevent what you want to prevent.
Upvotes: 3