This post is meant to clarify a few key concepts about Unix filesystems such as directory permissions, hardlinks and symlinks.
Q: If I chmod 777 a file, can someone delete it ?
A: No. To explain that, let’s first talk about directories. You can imagine a directory as a special file which would have one line for each file contained in that directory. On each such line, there would be the inode number, and the name of the matching file.
Deleting a file would be like removing a line from that special directory file which means that you need write permission on the directory containing the file to do so.
Q: What about that 777 mode /tmp directory ? Won’t someone delete all my files then ?
A: No. /tmp ‘s permissions are not actually 777 but 1777. That “1” is the sticky bit which materialize by the “t” flag showing up in “ls -l”. That sticky bit means that only the owner of the file is allowed to delete it.
kattoo@roadrunner ~ % ls -ld /tmp drwxrwxrwt 10 root root 4096 Dec 8 21:53 /tmp/
Q: Knowing that bit about directories being special files, how would you implement a hard links ?
A: Simply have 2 “special file directories” having a line with the same inode number and different (or same !) file names. There you go, alternate filenames for the same on-disk content.
Q: But then, if I delete a file with a hardlink, the “other” filename will point to no data ?
A: No. The inode contains quite a few informations : dates, permissions, owner, group and such as well as the number of hardlinks. Every time you delete such a hardlink, this counter is decremented. Everytime you create a hardlink, the count is incremented. The actual content of the file is only actually deleted when the count reaches 0.
Q: How about soft links (aka symbolic links aka symlinks) ?
A: A symlink is yet another special kind of file. You can imagine that it’s a file which contains the name of another file. Anyone accessing the symlink will actually access the content of the file which name is in the symlink special file. This name resolution being done in-kernel, it’s mostly transparent for userland processes. Notice that you could place the name of a non-existing file in the symlink (dead link !), which is not possible with a hardlink.
One thought on “Unix 101 : Filesystem basics & Special files”
In your answer to the first question you should clarify that no one can delete the file, but everyone can delete the content of that file by simply doing:
$ > file
Comments are closed.