Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the file mutex in Linux? How to implement it?

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?

like image 688
Lai Yu-Hsuan Avatar asked Jan 25 '26 08:01

Lai Yu-Hsuan


1 Answers

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.

like image 120
Omnifarious Avatar answered Jan 27 '26 00:01

Omnifarious



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!