Can anyone help me to understand the logic behind the link value being "2" for the first time when we create any folders/ directory in linux.
I searched a lot , but couldn't get satisfactory logic
Can anyone help me to understand the logic behind the link value being "2" for the first time when we create any folders/ directory in linux.
I searched a lot , but couldn't get satisfactory logic
Every directory has link count at least two due to
.
)Example: Suppose within some base directory there is a directory foo
:
$ ls -i /basedir
1056868 foo
$ ls -ia /basedir/foo
1056868 . 1056849 ..
The ls
option -i
shows the inode numbers of the directory entries, the option -a
shows entries that begin with a dot (ls
does not show those by default). Note that /basedir/foo
and /basedir/foo/.
have the same inode number. Since there are (at least) two different references to the according inode, the link count for that inode is two (or more).
The fundamental design of the Unix filesystem goes back to the early days. It is described in the paper The UNIX Time-Sharing System by Dennis M. Ritchie and Ken Thompson.
The designers wanted to be able to refer to the current directory, and to have a way to go from a directory to its parent directory. Rather than introduce special shell syntax, they decided to use a feature that already existed anyway: directories can contain entries for other directories, so they decided that an entry with the special name .
would always point to the directory itself, and an entry with the special name ..
would always point to a directory's parent. For example, if the root directory contains a subdirectory called foo
, then foo
's ..
entry points to the root directory and foo
's .
entry points to foo
itself.
Thus a directory's link count (the number of directory entries pointing to it) would always be 2 for a directory with no subdirectory: the expected entry in the parent directory, plus the .
directory. Each subdirectory adds 1 to the link count due to the ..
entry.
The special entries .
and ..
were originally created by the mkdir
command by mucking with the on-disk representation of the filesystem directly. Later systems moved this into the kernel. Today, many filesystems don't include .
and ..
entries in the on-disk representation anymore. The filesystem driver doesn't need .
, and doesn't need ..
either if it always remembers the location of a directory's parent (which increases memory consumption a bit, negligible by today's standards but not by the 1970's standards). In filesystems that include on-disk .
and ..
entries, the filesystem driver ensures that these entries are always present. In filesystems that don't include these entries in the on-disk representation, the filesystem driver pretends that these entries are present.