18.2 What's Really in a DirectoryBefore you can understand moving and copying files, you need to know a bit more about how files are represented in directories. What does it mean to say that a file is really "in" a directory? It's easy to imagine that files are actually inside of something (some special chunk of the disk that's called a directory). But that's precisely wrong, and it's one place where the filing cabinet model (1.19 ) of a filesystem doesn't apply. A directory really is just another file, and really isn't different
from any other data file.
If you want to prove this, try the command
So a directory is really just a list of files. It contains filenames and inode numbers (1.22 ) . That is, we can visualize a directory like this: The file named . is inode 34346 The file named .. is inode 987 The file named mr.ed is inode 10674 The file named joe.txt is inode 8767 The file named grok is inode 67871 The file named otherdir is inode 2345 So when you give a filename like grok , the kernel looks up grok in the current directory and finds out that this file has inode 67871; it looks up this inode to find out who owns the file, where the data blocks are, and so on. What's more, some of these "files" may be directories in their own
right. In particular, that's true of the first two entries:
Now that you know what a directory is, let's think about some basic operations. What does it mean to move, or rename, a file? If the file is staying in the same directory, the mv command just changes the file's name in the directory; it doesn't touch the data at all. Moving a file into another directory takes a little more work, but not much. A command like mv dir1/foo dir2/foo means "delete foo 's entry in dir1 , and create a new entry for foo in dir2 ." Again, UNIX doesn't have to touch the data blocks or the inode at all. The only time you actually need to copy data is if you're moving a file into another filesystem. In that case, you have to copy the file to the new filesystem; delete its old directory entry; return the file's data blocks to the "free list," which means that they can be re-used; and so on. It's a fairly complicated operation, but (still) relatively rare. (On some old versions of UNIX, mv won't let you move files between filesystems.) Now let's see if you've understood. How does UNIX find out the name of
the current directory? In our "current directory," there's an entry
for Complicated? Yes, but if you understand this, you have a pretty good idea of how UNIX directories work. - |
|