Monday, February 6, 2012

Hard Link Vs Symbolic(Soft) Link

Hard Link
  • Hard Link is a mirror copy of the original file.
  • Hard links share the same inode value. Hence same file permissions.Even if original file is deleted, hard links to the file are not affected.
  • Cannot create hard links on directories. 
  • Cannot create hard links across filesystems.
  • Backup of the hardlink would be the size of the file, while with the symlink only the link itself would be backed up.
  • Size of hardlink is equal to the size of the original file. Hence, creation of hardlink increases disk space usage.
Soft Link
  • Soft Link is a symbolic link to the original file.
  • Soft Links will have a different inode value from the original file. Hence different file permissions.
  • If original file is deleted, soft link fails.
  • Can create soft links on directories
  • Soft links can cross file systems
  • Size of softlink is the number of characters in the name of softlink
More about links

Creation of Hard link to file test.txt
$ ln test.txt  htest.txt

 Creation of Soft link to file test.txt
$ ln -s test.txt   ltest.txt



Let us examine the size of files

$ ls -l *test.txt
-rw-rw-r--. 2 ghost ghost 452263 Feb  7 01:38 htest.txt
lrwxrwxrwx. 1 ghost ghost      8 Feb  7 01:45 ltest.txt -> test.txt
-rw-rw-r--. 2  ghost ghost 452263 Feb  7 01:38 test.txt



There are 8 characters in the soft link ltest.txt. Hence the size of soft link is 8.

Let us examine the inodes of the files

$ ls -i *test.txt
263871 htest.txt  
262315 ltest.txt  
263871 test.txt

We can see that hard link(htest.txt) and original file(test.txt) share the same inode value 263871


To find files having hard links

$ find . -type f -links +1

Why hard links cannot be created on directories?

When a hard link is created to a directory, it increases the reference count for that directory.Let us examine what happens if hard links can be created for a directory - Take the following case a/b/c -> a. Here c is hard link to directory a. So a loop is created here, where subdirectory c points to grandparent directory a. So deleting a directory or traversing a directory for commands like find & du, are every expensive operations on disk somtimes causing to go on infinite recursion because of loop.

In case of creating a softlink for a directory, the reference count of the original directory is not affected. Hence soft link does not prevent the original directory being deleted and removed from disk. Also kernel does not follow symlinks for traversal operations like du or find.

No comments:

Post a Comment