Hard Links Vs Soft Links

 

1. Hard Links

📌 Definition

A hard link is another name (directory entry) that points to the same inode (same actual file).


🔑 Key Idea

👉 A file =

  • inode (actual file data + metadata)

  • name (directory entry)

👉 Hard link creates:

multiple names → same inode

📖 Example

echo hello > file ln file file2

Now:

  • file and file2 → same file

Check inode:

ls -i file file2

Output:

67158084 file 67158084 file2

✔ Same inode → same file


🔄 Behavior

  • Changing one file affects the other:

echo hi >> file2 cat file

✔ Both show updated content


🔢 Reference Count

  • Each inode keeps a link count

  • Incremented when a hard link is created

  • Decremented when a link is removed


❗ Deletion Logic

rm file

👉 Only removes one link

✔ File still exists via file2

👉 Actual deletion happens when:

link count = 0

🚫 Limitations of Hard Links

  • ❌ Cannot link directories (to avoid cycles)

  • ❌ Cannot link across file systems

  • ✔ Only works within same filesystem


2. Soft Links (Symbolic Links)

📌 Definition

A symbolic link is a special file that stores the path of another file


📖 Example

ln -s file file2

Now:

  • file2 → points to "file" (path)


🔑 Key Idea

👉 Soft link:

file2 → "file" (path stored inside)

👉 Not the same inode


📊 Check Details

ls -al

Output:

-rw-r----- file lrwxrwxrwx file2 -> file
  • l → symbolic link

  • Stores path as data


🔍 Internal Structure

  • Soft link is a separate file

  • Contains:

    • Pathname of target file

Example:

file2 contains "file"

⚠️ Dangling Links

rm file cat file2

❌ Error: file not found

👉 Because:

  • Soft link points to path

  • Path no longer exists


Key Differences 

FeatureHard Link    Soft Link
Points to    Inode    File path
Inode number    Same    Different
File type    Regular file    Special file
Cross filesystem    ❌ No    ✔ Yes
Directory linking    ❌ No    ✔ Yes
Survives original deletion    ✔ Yes    ❌ No
Storage    No extra space    Stores path

 Conceptual Diagram

Hard Link

file ──┐ ├──> inode (data) file2 ─┘

Soft Link

file2 ──> "file" ──> inode (data)

 Why unlink() Makes Sense

👉 Now you understand:

  • unlink() removes:

    • name → inode mapping

  • Not the file itself immediately

✔ File removed only when:

link count = 0

Summary

Emphasize to students:

  • Hard link = multiple names for same file

  • Soft link = shortcut to another file

👉 Core distinction:

  • Hard link → direct reference

  • Soft link → indirect reference (path-based)

Q: What happens if original file is deleted?

  • Hard link → still works

  • Soft link → broken (dangling)

Comments

Popular posts from this blog

Operating Systems OS PCCST403 Semester 4 BTech KTU CS 2024 Scheme

Introduction to Operating System -Virtualization, Concurrency, and Persistence

Operating Systems PCCST403 Scheme and Syllabus