How do directories map file names to inodes, and what is the difference between a hard link and a soft link?
MediumConceptFile Systems & Disk Scheduling
Answer
A directory is a special file containing entries, each mapping a file name to an inode number. Paths are resolved one part at a time: for /home/user/a.txt, the kernel starts at the root directory's inode and looks up home, then user, then a.txt. A hard link is simply another directory entry pointing to the same inode. A soft (symbolic) link is a separate small file whose content is the path of its target.
- Hard link: all names are equal. The inode's link count records how many names exist, and the data is freed only when the count reaches 0 and no process has the file open. Hard links cannot cross file systems and normally cannot point to directories.
- Soft link: has its own inode and can point to directories and to other file systems, but it becomes a dangling (broken) link if the target is deleted or moved.
Example:
$ echo hello > a.txt
$ ln a.txt hard.txt # same inode, link count becomes 2
$ ln -s a.txt soft.txt # new inode that stores the path "a.txt"
$ rm a.txt
$ cat hard.txt # prints: hello
$ cat soft.txt # cat: soft.txt: No such file or directory
More in File Systems & Disk Scheduling
| # | Problem | Platform | Difficulty | Open | 1st1st Visit | 2nd2nd Visit | RevRevise |
|---|---|---|---|---|---|---|---|
| 1 | What is an inode, and what information does it store? | Concept | Medium | Read the answer to What is an inode, and what information does it store? | |||
| 2 | How do directories map file names to inodes, and what is the difference between a hard link and a soft link? | Concept | Medium | Read the answer to How do directories map file names to inodes, and what is the difference between a hard link and a soft link? | |||
| 3 | What are the contiguous, linked and indexed file allocation methods? | Concept | Medium | Read the answer to What are the contiguous, linked and indexed file allocation methods? | |||
| 4 | Compare FCFS, SSTF, SCAN and C-SCAN disk scheduling. | Concept | Hard | Read the answer to Compare FCFS, SSTF, SCAN and C-SCAN disk scheduling. |