Hard Links and Symbolic Links
Hard links
A hard link is an additional directory entry that points to the same inode as an existing file. Created with link() or ln:
ln original.txt link.txt
After this, original.txt and link.txt are completely equivalent — both are names for the same inode. The inode’s link count increases to 2. Deleting original.txt (unlink) reduces the link count to 1; the file persists under link.txt. The data is freed only when the link count drops to 0 AND no process has the file open.
Hard links have restrictions:
- They cannot span file systems (inode numbers are unique only within a file system).
- They cannot link to directories (except for
.and.., which the kernel creates automatically). This prevents cycles in the directory tree.
Symbolic links (soft links)
A symbolic link is a special file whose content is a path string. Created with symlink() or ln -s:
ln -s /etc/config/app.conf ./app.conf
The symlink’s own inode marks it as type S_IFLNK. Reading the symlink (with readlink()) returns the path string; opening it causes the kernel to follow the path transparently.
Symlinks can span file systems and can point to directories. They are not reference-counted — if the target is deleted, the symlink becomes a dangling symlink (or “broken link”), and opening it fails with ENOENT.
Hard vs soft: a comparison
| Property | Hard link | Symbolic link |
|---|---|---|
| Nature | Multiple names for the same inode | A separate inode containing a path string |
| Deletion safety | File survives as long as one link remains | Dangles if target is deleted |
| Cross-file-system | No (inode numbers are local) | Yes |
| Points to directories | No | Yes |
| Storage overhead | One directory entry (negligible) | One inode + one data block (typically) |
| Detectable by | Same inode number (ls -i) | ls -l shows -> target |
Symlinks and path resolution
If a symlink appears as a path component, the kernel replaces the remaining path components with the symlink’s target and restarts resolution. Example:
ln -s /usr/share /home/alice/share
cat /home/alice/share/doc/README
The kernel resolves /home/alice/share, discovers it is a symlink to /usr/share, and continues resolution from /usr/share/doc/README. The directory traversal continues — if /usr/share is also a symlink, resolution follows it too, up to the system limit (typically 40 hops).
Summary
- Hard links: additional name for the same inode. Equal status. Deleted only when link count reaches 0.
- Symlinks: a separate file containing a path. Can dangle. Can cross file systems and point to directories.
- Hard links are simpler and more robust; symlinks are more flexible.
- The inode-name separation is the unifying concept: hard links share the inode; symlinks reference it by name.