r/linuxquestions • • 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?

176 Upvotes

62 comments sorted by

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.

19

u/ThiefClashRoyale Sep 22 '20

How do you get it back if its gone but in use?

163

u/cloveistaken Sep 22 '20

Very good question that new people using Linux should know in case of accidental file deletion. I wished I had known this sooner.

Look for any running process that have the file descriptor of the deleted file. Check /proc/PID/fd/FD, it should show something like this

$ file /proc/7462/fd/3
/proc/7462/fd/3: symbolic link to /tmp/lmao/example.txt (deleted)

Then you can read the file normally with cat, or restore it with cp.

23

u/DrLota Sep 22 '20

Oh my, thank you kind human for this tip.

10

u/chmod--777 Sep 23 '20

Fuck, you can just cp it from /proc? That's awesome, thanks for the tip! I love the VFS stuff on linux

7

u/throw07052014 Sep 22 '20

Dude, this comment is great! Thank you very much for sharing this!

9

u/beaubeautastic Sep 23 '20

or use ln. that way, it just puts the name back instead of copying it to a new file.

3

u/Willy-the-kid Sep 23 '20 edited Sep 23 '20

I just tried it to learn how and in /proc/PID/fd/ there's 3 empty files (0 1 2) ls -l said they're all a link to /dev/pts/0 which gives the same non terminating "error" when read no result no prompt why is this

19

u/cloveistaken Sep 23 '20

My previous reply is kind of aiming for people with somewhat basic knowledge about it, and it's fine if you didn't get it.

So basically, in Linux, you can't interact directly with a file. You need to open it first before read/write to it. The action of opening a file gives us something call a "file descriptor", which is just integers from 0.

Consider a normal text file, which is just a chunk of 0s and 1s in your disk.

What the first reply was saying is that, the file descriptor is in fact just a pointer, pointing to such chunk of memory. After opening the file by specifying the filename, the filename itself is not important anymore, because you only need to work with the file descriptor, which is still pointing to that memory. Even if you delete the text file, Linux kernel wouldn't scrap that chunk of memory yet, because the running program might still need to work with it.

Then, we accidentally delete a file, and we know there is a program is still using that particular (e.g: notepad is open), we can find a way to retrieve it back, by somehow get the opened file descriptor and locate the chunk of memory.

Where is the information about this file descriptor stored ? The running Linux kernel indeed, and /proc (procfs) is a special filesystem of Linux that exposes some of the information of it. Particularly, /proc/PID/fd/ contains all the opened file descriptors of the running process, which includes the "deleted" text file. Hence my comment.

For the other part of your question, all processes have 3 opened file descriptors by default: stdin (0), stdout (1), stderr (2), which at the moment is probably your terminal emulator a.k.a /dev/pts/0.

If you want to test what I was talking about, create example.txt and compile/run the following program.

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main()
{
  int fd = open("example.txt", 0);
  while (1) {}
}

Then open another terminal, delete example.txt and do what I said before.

1

u/humnsch_reset_180329 Sep 23 '20

I did echo Hello > /proc/xxx/fd/2 in your scenario and was mind blown!

2

u/michaelkrieger Sep 23 '20

A tty is a native terminal device, the backend is either hardware or kernel emulated. A pty (pseudo terminal device) is a terminal device which is emulated by an other program (example: xterm, telnet, screen, or ssh are such programs). A pts is the slave part of a pty.

Those are standard input (your keyboard or the input from a pipe), standard output (your screen or output from a pipe) and standard error (by default also your screen). When you run a program these are each connected to somewhere- usually the running terminal.

The program you are looking at doesn’t have open file handles

1

u/[deleted] Sep 23 '20

stdin, stdout, and errout are always assigned when a program is started. Those have file handles of 0, 1, and 2 for stdin, stdout, and errout.

If the program is started with "program <input >output ?errout" , those three files are stripped out of the "main( int argc, char *args[]) {}" command line and assigned by the shell at startup. You can still read or write to the stdin, stdout, and errout by using the file handles of 0, 1, and 2 or the C/C++ values of stdin, stdout, errout.

2

u/ccAbstraction Sep 23 '20

This would have been so helpful that time, I accidentally deleted my conky config and just made a memory dump and scrolled through the data in cat until I found the config in plain text.

-2

u/SpAAAceSenate Sep 22 '20

For various security and POSIX-standards reasons it's not super easy and requires root. You have to use a filesystem debugger to access the inode directly. There's no way normally to access an inode directly by ID without a path. Imagine permissions like the x (traversal of directory) attribute. "Where" a file is influences the permissions that govern it, so if a file is "nowhere" because it has no path, then how would the kernel decide if a program attempting to access it should be able to? (Permissions are checked when a file handle is first given to an app, thus why a program with it already open can continue to access it, because they were given their handle before the final path was deleted)

I hope I explained that well. Did that make sense?

1

u/ThiefClashRoyale Sep 22 '20

One time I deleted the hard disk of a VM while ot was running and the vm was fine but I couldnt get the file back. I tried googling but wondered if you knew as you suggested it was possible. Once I turned off the VM it was gone forever.

5

u/sunflsks Sep 22 '20

An inode doesn't actually contain the data, but it contains everything else like permissions, metadata, etc.

4

u/pobrn Sep 22 '20

I didn't meant to imply that, maybe I wasn't clear enough.

4

u/pnht Sep 22 '20

actually it does. The inode contains a filesysten id and an "inode number" the inode number points to the file data on the file system. If you "delete" the inode (by reducing the link count to zero and closing the file in any process that has it open), the filesystem deletes the inode. At that point the data is still on the disk (until another file overwrites it) but there is nothing to tell us where the file data is.

6

u/sunflsks Sep 23 '20

Exactly. An inode doesn’t hold the actual data, just a pointer to the data

8

u/[deleted] Sep 23 '20

I learned more from this thread, as compared to my University.

3

u/CodenameLambda Sep 23 '20

Stuff like that isn't just interesting but also useful to know - trusting magic is always dangerous. As such I think it should be taught at unis (and it is at the one I go to, luckily).

1

u/SweeTLemonS_TPR Sep 23 '20

Did you take a class focused on Linux? All of this is covered in entry-level cert books, and I know guys with Associate's degrees who were getting into kernel code in their Linux classes. I'd be very surprised if they weren't hitting on at least as much as those certs in every Linux class. I wouldn't expect it in most CS classes, though.

5

u/patatahooligan Sep 22 '20

What you describe here is one of the main reasons linux updates are so simple. You can upgrade binaries even as they're running so no need to hook the update process into the boot/shutdown process.

3

u/CodenameLambda Sep 23 '20 edited Sep 23 '20

If you'd overwrite the original data instead of creating a new file in the old file's place, would that change the running binary (since I assume it's mmaped, though I don't know; plus I don't know if there are any features of mmap to avoid other things to change your stuff while you're reading it, which could presumably be used for running executables)

EDIT: I tried testing it, but apparently you cannot even open a running executable for writing :( EDIT 2: Digging shows that the "text file busy" error message is actually precisely for writing to running executables / trying to run an executable that's opened with writing

1

u/patatahooligan Sep 23 '20

According to this you can actually cause problems by modifying a long shell script because it is read intermittently. But the answer is quite old and might not apply anymore.

If you decide to try it out, set up some sort of restricted environment because I don't think you're guaranteed a crash. Instead, the script might behave in unexpected ways and damage your system or data.

1

u/zurohki Sep 23 '20

I've had shell scripts derp out because I modified them while they were running, and then the shell has started reading the new shell script at the point it was up to in the old script, which might be halfway through a line or in the middle of a comment.

1

u/[deleted] Sep 23 '20

Take a look at the "dup" and the "dup2" system calls to add more confusion to your question.

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

u/[deleted] 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?

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

https://unix.stackexchange.com/questions/49299/what-is-linux-doing-differently-that-allows-me-to-remove-replace-files-where-win

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

u/[deleted] 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

https://gavv.github.io/articles/file-locks/

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 ~filename was. 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

u/[deleted] 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

u/Phydoux Sep 23 '20

Yup. That's exactly the point I was conveying.

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

u/Fakin-It Sep 22 '20

haha nice try Brad Smith

0

u/[deleted] Sep 22 '20

[deleted]

1

u/[deleted] 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

u/[deleted] Sep 25 '20

Thank you, that's a useful tidbit I wasn't aware of.

0

u/[deleted] Sep 22 '20

[deleted]

3

u/cyber_rigger Sep 22 '20

(Linux)

touch test1

gedit test1

..... on another terminal

mv test1 test2

1

u/yun0likeme Sep 22 '20

Where's your file lock?