The best way to understand what links are is to look at an example. Let's create a (regular) file:
$ pwd /home/queen/example $ ls $ touch a $ ls -il a 32555 -rw-r--r-- 1 queen queen 0 Aug 6 19:26 a
The -i
option of the
ls command prints the inode number, which is the first
field on the output. As you can see, before we created file
a
, there were no files in the directory. The other
field of interest is the third one, which is the number of file links
(well, inode links, in fact).
The touch a command can be separated into two distinct actions:
creation of an inode, to which the operating system has given the number 32555, and whose type is the one of a regular file;
creation of a link to this inode,
named a
, in the current directory
(/home/queen/example
). Therefore the
/home/queen/example/a
file is a link to
the inode numbered 32555, and it's currently the only one: the
link counter shows 1
.
$ ln a b $ ls -il a b 32555 -rw-r--r-- 2 queen queen 0 Aug 6 19:26 a 32555 -rw-r--r-- 2 queen queen 0 Aug 6 19:26 b $
We create another link to the same inode. As
you can see, we didn't create a file named b
.
Instead, we just added another link to the inode numbered 32555 in the
same directory, and attributed the name b
to this new
link. You can see on the ls -l output that the link
counter for the inode is now 2 rather than 1.
$ rm a $ ls -il b 32555 -rw-r--r-- 1 queen queen 0 Aug 6 19:26 b $
We see that even though we deleted the
“original file”, the inode still exists. But now, the only
link to it is the file named
/home/queen/example/b
.
Therefore a file in UNIX® has no name; instead, it has one or more link(s) in one or more directories.
Directories themselves are
also stored in inodes. Their link count coincides with the number
of sub-directories within them. This is due to the fact that there
are at least two links per directory: the directory itself
(represented by the entry .
) and its parent
directory (represented by ..
). So a
directory with two sub-directories will have at least four links:
.
, ..
and links for each
sub-directory.
Typical examples of files
which are not linked (i.e.: have no name) are network connections.
You will never see the file corresponding to your connection to
the Mandriva Linux web
site in your file tree, no matter which directory you look
in. Similarly, when you use a pipe in the shell
, the
inode corresponding to the pipe exists, but it is not
linked. Temporary files are another example of inodes without
names. You create a temporary file, open it, and then remove
it. The file exists while it's open, but nobody else can open it
(as there is no name to open it). This way, if the application
crashes, the temporary file is removed automatically.