r/linuxquestions • u/[deleted] • Sep 22 '20
How does Linux handle operations on files that are in use?
Renaming files and folders in Windows is a gigantic pain if any files are being used. I just realized I am able to freely move and rename files in Linux while they're open, which is fantastic. What does Linux do differently from Windows to allow that?
29
u/OweH_OweH Sep 22 '20
https://en.wikipedia.org/wiki/File_locking and https://en.wikipedia.org/wiki/File_descriptor
The information in those two articles should start you down the right rabbit hole.
25
u/edman007-work Sep 22 '20
For the differences you're talking about, it helps to understand what a file is. The filesystem saves every file into an inode, which is simply a collection of data without much more than a number to identify it. Filenames are separate things, and point to inodes. You can have multiple filenames pointing to the same inodes (commonly known as hardlinks).
Functionally, when opening a file in linux, you read the filename and open the inode (the kernel handles this under the hood). but moving or deleting a filename doesn't really affect the inode, they are separate, so you can move and delete files while programs are writing to them.
Deleting is a little special, the filename is deleted when rm the file, the inode is deleted when there are both no filenames pointing to it, and no processes with the inode open. Because of this you can have a program writing to a file, and you can delete it, and the program will be able to continue writing to the file, and it will still consume disk space. When you close the program then the inode and it's data is deleted.
2
u/mchilds83 Sep 22 '20
If the filename was deleted while a program had the file open for editing, and if it wrote changes to that file then closed the file, would it just be that no filename link exists to locate the file so it appears deleted, or would the inode data be purged making it impossible to recover the file? Or would it recreate the filename link as a courtesy since it updated the inode data?
5
u/symcbean Sep 22 '20
The fie exists and occupies space as long as there is at least one file handle open, even if it has no directory entry. But when the last file handle is closed the file is implicitly deleted and the space freed up.
1
u/SweeTLemonS_TPR Sep 23 '20
If the program wrote to the file (like a DB write, so it was saved and committed, not just added text without a save), it should recreate the file name. I just did it with vim.
I created "test1" wrote "blah blah blah" and saved. Then I opened it again, deleted "test1" and ".test1.swp," and exited vim with :wq, and "test1" appeared back in the current directory. I don't see why that would be any different for any other application.
1
u/symcbean Sep 23 '20
Editing a file is **NOTHING** like a DB write - vim loads the file into memory AND CLOSES IT while you are editing it. You can test this yourself with `lsof`. So yes, it will recreate a deleted file from the copy it holds in memory (and the .*.swp file).
1
u/SweeTLemonS_TPR Sep 23 '20
I know it’s nothing like a DB write. I said “saved and committed” trying to differentiate between appending to the file.
My example is flawed in a lot of ways, but my broader point was “it depends on the application and how it’s handling the data.” I did a terrible job of getting that point across.
1
u/sunflsks Sep 22 '20
An inode has everything about a file (permissions, owner, etc) BUT the actual data, which is stored elsewhere.
1
u/TiagoTiagoT Sep 22 '20
What happens if you cut the power before the program is closed but after the file has been deleted?
2
u/sunflsks Sep 22 '20
It would probably be deleted, as when the computer boots up again all references to the file would be gone.
2
Sep 23 '20
Most filesystems has some journals, where it logs the latest state of the FS and if something changed on the FS and its not reflected in the journal, this inconsistency will be picked up by fsck and it will ask about it, or try to repair it automatically.
0
u/TiagoTiagoT Sep 22 '20
So the system just forgets there is a file there?
4
u/edman007 Sep 22 '20 edited Sep 23 '20
Might become and orphaned inode, fsck will find these and give them a filename in /lost+found
2
u/SweeTLemonS_TPR Sep 23 '20
It doesn't forget. You deleted it. It's only there in the memory of some application that wasn't given the chance to create the file again.
1
u/TiagoTiagoT Sep 23 '20
So the file could be overwritten while it's being used by a program since everyone else thinks it's just unused space?
1
0
u/sunflsks Sep 22 '20
Yeah, since the process that had the file open was killed, there’s no references to it anymore
6
u/AiwendilH Sep 22 '20
This is simplified and the implementation details are actually a bit more complex but I think it gives a good idea what goes on and what pitfalls it has:
Imagine a file as two parts...the actual data and a handle pointing to the data. If a program opens a file it gets such a handle and by this gets access to the real data. In a way a filename is also just such a handle...behind a filename is not really the data itself but rather a pointer to the data. That is how hardlinks work...they create two filenames pointing to exactly the same data (not like symlinks that create a second filename pointing to another filename). As long as one such handle exists the data is not deleted. So that means if you have a file accessible with two hardlinks you can delete one of the hardlinks and the data still exists. And as said above..a program gets an own handle if it opens a file...so even if you delete the filename to that data the program doesn't care as it keeps accessing the data through the handle it already has...and the data is not going to be deleted as long as that open file handle from the program exists.
This has of course consequences. For example if a program has a file "text.txt" open, you delete that file and create a new one the program (usually) doesn't care, it won't save to the new file but also won't complain that you deleted the file. Just when you close the file in the program or close the program all the data is lost. (Some program check specifically for file changes though like most text editors...but that is something programs have to consciously do, not something that comes from the OS)
Another consequence is for example with updates. If a program uses a library and that library gets updated by you package manager the program won't care at all. Until it is restarted it will still use the old library..what can be a real problem if the update was due to a security issue. That is why some distros have tools to identify such long running programs and restart them.
Or in the past (per-systemd) with own log-daemons cycling and making backups of logfiles also ran into a problem there. That is why a lot of daemons misuse SIGHUP (https://en.wikipedia.org/wiki/Signal_(IPC)#SIGHUP) to reload their files..it allows to tell for example a log-daemon that you archieved the log-files and it should create new file handles to access new ones.
3
u/Yithar Sep 22 '20
The file is kept on the disk in the multilevel structure called i-node. Each i-node has an unique number on the single filesystem. The i-node structure keeps different information about a file, like its size, data blocks allocated for the file etc., but for the sake of this answer the most important data element is a link counter. The directories are the files that keep records about the files. Each record has the i-node number it refers to, the file name length and the file name itself. This scheme allows one to have 'pointers', i.e. 'links' to the same file in different places with different names. The link counter of the i-node actually keeps the number of links that refer to this i-node.
What happens when some process opens the file? First the open() function searches for the file record. Then it checks if the in-memory i-node structure for this i-node already exists. This may happen if some application already had this file opened. Otherwise, the system initializes a new in-memory i-node structure. Then the system increases the in-memory i-node structure open counter and returns to the application its file descriptor.
The Linux library call to delete a file is called unlink. This function removes the file record from a directory and decrements the i-node's link counter. If the system found that an in-memory i-node structure exists and its open counter is not zero then this call returns the control to the application. Otherwise it checks if the link-counter became zero and if it does then the system frees all blocks allocated for the i-node and the i-node itself and returns to the application.
2
u/bigfig Sep 23 '20 edited Sep 23 '20
Not all filesystems are the same but typically with Linux the actual file or directory (folder) is really a numeric entry known as an inode, and one or more names are associated with that number on a device. Only when the last name is dis-associated is the file actually marked for removal. There is usually no mandatory locking on Linux/Unix, so a directory name could be removed even while you are in that directory, so when you change away and then try to change back, it will be gone. Locking, when requested, is advisory, so checking if a file is marked as locked is optional. My experience is advisory locks cause less problems than mandatory locks.
1
Sep 22 '20
Um.... not sure what's your background on OS and file system development and what type of answer you would expect (except the obvious "windows sucks"), but here is a detailed description about file locking in linux
1
u/Phydoux Sep 22 '20
There's a difference between a program actually running on your system and the config file or script that loaded it. Once the configuration file or script has been executed (told the system how to load the program), the script and config file don't stay in memory. The actions that it launched has. The loaded program pulls the info from the config file and then it's done with it until you restart the program.
Take, your .bashrc file for instance. That file is loaded whenever you open a terminal. Let's say you have your terminal open. Your .bashrc file is read. You make a change to .bashrc and that change isn't implemented until you open a terminal again. You could keep that old terminal open, start another terminal and the new terminal will use that new command or configuration that you added. But the old one won't know what that new command is.
A simple way to test this out is to open a terminal. Edit your .bashrc file and add
alias q='exit'
Save the .bashrc file and open a second terminal (keeping the original terminal open). type q in the old terminal and nothing happens (it will give you an error probably) because it loaded the configuration file before you rewrote it. So it has no idea what to do with q. Type q in the new terminal and the terminal should close. This one read the newer .bashrc file when it loaded and knows what to do with q.
You can do this same thing without opening 2 terminals. Open a terminal, edit .bashrc file and add
alias e='exit'
Save the .bashrc file and then type bash in that already opened terminal. If you have something like neofetch running then you'll see neofetch come up again and you'll see the command prompt. This means that you've run bash on top of bash. So you essentially have 2 bash commands running in one terminal.
Type e at that command prompt. You'll probably see the word exit and then another command prompt will appear again. Now you've dropped to the first level command prompt. Type e again and you should get an error that the command does not exist. That is because it doesn't exist in that instance of the terminal.
Confusing but it makes sense when you think about it.
3
u/CBSmitty2010 Sep 22 '20
While that is good information that doesn't address op's original question about file handles being open and being able to edit the file.
1
u/Phydoux Sep 23 '20
That all depends on what files OP is editing or renaming. I used the above analogy to illustrate what happens with most of the files in the users /home directory. Those files are mostly configuration files. If OP is renaming files in directories such as /etc, /bin, or /usr/bin then that's probably not the best idea.
But the /home directory is very easy to rename files in while the files are open because they are loaded into memory and then are not touched until the programs that need them are reloaded. Office documents are easy to rename while they're open. But saving the open file will just recreate the old fine name unless you do a save as. Also, you can open a calc file, delete that file and save it as a new file. I've done that quite often especially when I completely changed my file naming scheme a couple of years ago. I had a TON of documents from Windows XP (Yes, I've been dragging files along for that long) that I recently renamed because I was using a more numeric naming scheme for my documents. LibreOffice (and MS Office as I recall) opens a temp file for the file you're working on. You can change the opened file in LibreOffice any way you'd like. The original file isn't touched until you save that file. It's a safety feature to keep the file you're working on from becoming corrupt during editing.
MS Office worked like that for several versions. I first noticed it I think in Office 97. I was working on a rather large Access file and didn't know what the
~filenamewas. I tried to delete it but couldn't because that's the file Access was using in the program instead of the one I opened.I'm not exactly sure of the percentage of files in my /home directory I can rename while I'm editing them but I'm sure it's a high percentage.
2
Sep 23 '20
The is a case of "you can't teach an old dog new tricks". Your original bash window is the "old dog" and the new session is the "new tricks". You can't send the new commands up the program stack.
1
1
u/Dandedoo Sep 23 '20
Be aware that if you move an open file, then save the open file (say in a text editor), you will now have 2 files.
-2
u/khleedril Sep 22 '20 edited Sep 22 '20
Truth be known, noone outside a select few at Microsoft actually knows how Windows works internally--the source code is not available. Suffice to say that the open source nature of Linux allows users to scrutinize and improve the kernel, hence the ultimately better functionality.
-1
0
Sep 22 '20
[deleted]
1
Sep 23 '20
sync is also the number 4 ID user in /etc/passwd. The sync command can be run from the login screen. This allows the sync command to be run without logging into the system.
1
0
Sep 22 '20
[deleted]
3
145
u/pobrn Sep 22 '20 edited Sep 22 '20
Very simply: a name is but a "link" to the actual file object (inode - it represents the file: permissions/owners/other metadata are stored in it), when a program opens a file, it gets a reference to that inode. As you can see, after opening the file, the name doesn't really matter, so it can be modified however you wish. You can even delete a file, and the program could still happily use it. In fact, if you delete a file, but a program has it open, then it's possible to recover the contents since a file is not truly deleted until all references to it cease to exist.